"use client";

import { useEffect, useState, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { useForm, type SubmitHandler } from "react-hook-form";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Shield, User, CheckCircle, AlertTriangle, Tag, ChevronRight } from "lucide-react";
import Link from "next/link";

interface UserProfile {
  id: string;
  name: string | null;
  email: string;
  currency: string;
  timezone: string;
  mfaEnabled: boolean;
}

interface ProfileForm {
  name: string;
  currency: string;
  timezone: string;
}

interface PasswordForm {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

function SettingsPage() {
  const searchParams = useSearchParams();
  const queryClient = useQueryClient();
  const defaultTab = searchParams.get("tab") === "security" ? "security" : "profile";
  const [profileMsg, setProfileMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [passwordMsg, setPasswordMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [mfaMsg, setMfaMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [disableToken, setDisableToken] = useState("");

  const { data: profile, refetch } = useQuery<UserProfile>({
    queryKey: ["user-profile"],
    queryFn: async () => {
      const res = await fetch("/api/user/profile");
      if (!res.ok) throw new Error("Failed to load profile");
      return res.json();
    },
  });

  const profileForm = useForm<ProfileForm>({
    defaultValues: { name: "", currency: "USD", timezone: "UTC" },
  });

  useEffect(() => {
    if (profile) {
      profileForm.reset({
        name: profile.name ?? "",
        currency: profile.currency,
        timezone: profile.timezone,
      });
    }
  }, [profile, profileForm]);

  const passwordForm = useForm<PasswordForm>();

  const updateProfile = useMutation({
    mutationFn: async (data: ProfileForm) => {
      const res = await fetch("/api/user/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error("Failed to update profile");
      return res.json();
    },
    onSuccess: () => {
      setProfileMsg({ ok: true, text: "Profile updated." });
      // Invalidate all cached queries so every page re-renders with the new currency
      queryClient.invalidateQueries();
      setTimeout(() => setProfileMsg(null), 3000);
    },
    onError: () => setProfileMsg({ ok: false, text: "Failed to update profile." }),
  });

  const changePassword = useMutation({
    mutationFn: async (data: PasswordForm) => {
      const res = await fetch("/api/user/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          currentPassword: data.currentPassword,
          newPassword: data.newPassword,
        }),
      });
      const body = await res.json();
      if (!res.ok) throw new Error(body.error ?? "Failed to change password");
      return body;
    },
    onSuccess: () => {
      setPasswordMsg({ ok: true, text: "Password changed." });
      passwordForm.reset();
      setTimeout(() => setPasswordMsg(null), 3000);
    },
    onError: (e: Error) => setPasswordMsg({ ok: false, text: e.message }),
  });

  const disableMfa = useMutation({
    mutationFn: async (token: string) => {
      const res = await fetch("/api/mfa/disable", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token }),
      });
      if (!res.ok) throw new Error("Invalid code");
    },
    onSuccess: () => {
      setMfaMsg({ ok: true, text: "MFA disabled." });
      setDisableToken("");
      refetch();
      setTimeout(() => setMfaMsg(null), 3000);
    },
    onError: () => setMfaMsg({ ok: false, text: "Invalid code. Try again." }),
  });

  const onProfileSubmit: SubmitHandler<ProfileForm> = (data) => updateProfile.mutate(data);
  const onPasswordSubmit: SubmitHandler<PasswordForm> = (data) => {
    if (data.newPassword !== data.confirmPassword) {
      setPasswordMsg({ ok: false, text: "Passwords don't match." });
      return;
    }
    changePassword.mutate(data);
  };

  const TIMEZONES = [
    "UTC", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles",
    "Europe/London", "Europe/Paris", "Europe/Berlin", "Asia/Kolkata", "Asia/Colombo",
    "Asia/Tokyo", "Asia/Singapore", "Asia/Dubai", "Australia/Sydney", "Pacific/Auckland",
  ];

  const CURRENCIES = ["USD", "EUR", "GBP", "LKR", "INR", "JPY", "AUD", "CAD", "SGD", "AED"];

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h1 className="text-2xl font-bold text-white">Settings</h1>
        <p className="text-slate-400 mt-1">Manage your account and security preferences</p>
      </div>

      {/* Quick links */}
      <Link
        href="/settings/categories"
        className="flex items-center gap-3 px-4 py-3 rounded-xl bg-slate-800/50 border border-slate-700/50 hover:bg-slate-800 hover:border-slate-600 transition-all group"
      >
        <div className="w-9 h-9 rounded-xl bg-violet-500/15 flex items-center justify-center">
          <Tag className="h-4 w-4 text-violet-400" />
        </div>
        <div className="flex-1">
          <p className="text-sm font-medium text-slate-200">Manage Categories</p>
          <p className="text-xs text-slate-500">Enable, disable, or create custom categories</p>
        </div>
        <ChevronRight className="h-4 w-4 text-slate-600 group-hover:text-slate-400 transition-colors" />
      </Link>

      <Tabs defaultValue={defaultTab}>
        <TabsList className="bg-slate-800 border border-slate-700">
          <TabsTrigger value="profile" className="data-[state=active]:bg-slate-700 data-[state=active]:text-white text-slate-400">
            <User className="h-4 w-4 mr-2" />Profile
          </TabsTrigger>
          <TabsTrigger value="security" className="data-[state=active]:bg-slate-700 data-[state=active]:text-white text-slate-400">
            <Shield className="h-4 w-4 mr-2" />Security
          </TabsTrigger>
        </TabsList>

        {/* Profile Tab */}
        <TabsContent value="profile" className="mt-4 space-y-4">
          <Card className="bg-slate-800/50 border-slate-700/50">
            <CardHeader>
              <CardTitle className="text-white">Profile</CardTitle>
              <CardDescription className="text-slate-400">
                Update your display name and regional preferences
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={profileForm.handleSubmit(onProfileSubmit)} className="space-y-4">
                <div className="space-y-1">
                  <Label className="text-slate-300">Full Name</Label>
                  <Input
                    {...profileForm.register("name")}
                    placeholder="Your name"
                    className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
                  />
                </div>

                <div className="space-y-1">
                  <Label className="text-slate-300">Email</Label>
                  <Input
                    value={profile?.email ?? ""}
                    disabled
                    className="bg-slate-800/50 border-slate-700 text-slate-500"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <Label className="text-slate-300">Default Currency</Label>
                    <select
                      {...profileForm.register("currency")}
                      className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                    >
                      {CURRENCIES.map((c) => (
                        <option key={c} value={c}>{c}</option>
                      ))}
                    </select>
                  </div>

                  <div className="space-y-1">
                    <Label className="text-slate-300">Timezone</Label>
                    <select
                      {...profileForm.register("timezone")}
                      className="w-full h-9 rounded-lg border border-slate-600 bg-slate-800 text-slate-200 px-3 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                    >
                      {TIMEZONES.map((tz) => (
                        <option key={tz} value={tz}>{tz}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {profileMsg && (
                  <div className={`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${
                    profileMsg.ok
                      ? "bg-emerald-500/10 border border-emerald-500/20 text-emerald-400"
                      : "bg-red-500/10 border border-red-500/20 text-red-400"
                  }`}>
                    {profileMsg.ok ? <CheckCircle className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
                    {profileMsg.text}
                  </div>
                )}

                <Button
                  type="submit"
                  disabled={updateProfile.isPending}
                  className="bg-emerald-600 hover:bg-emerald-500 text-white"
                >
                  {updateProfile.isPending ? "Saving…" : "Save Profile"}
                </Button>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Security Tab */}
        <TabsContent value="security" className="mt-4 space-y-4">
          {/* Change Password */}
          <Card className="bg-slate-800/50 border-slate-700/50">
            <CardHeader>
              <CardTitle className="text-white">Change Password</CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={passwordForm.handleSubmit(onPasswordSubmit)} className="space-y-4">
                <div className="space-y-1">
                  <Label className="text-slate-300">Current Password</Label>
                  <Input
                    type="password"
                    {...passwordForm.register("currentPassword")}
                    className="bg-slate-800 border-slate-600 text-white"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-slate-300">New Password</Label>
                  <Input
                    type="password"
                    {...passwordForm.register("newPassword")}
                    className="bg-slate-800 border-slate-600 text-white"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-slate-300">Confirm New Password</Label>
                  <Input
                    type="password"
                    {...passwordForm.register("confirmPassword")}
                    className="bg-slate-800 border-slate-600 text-white"
                  />
                </div>

                {passwordMsg && (
                  <div className={`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${
                    passwordMsg.ok
                      ? "bg-emerald-500/10 border border-emerald-500/20 text-emerald-400"
                      : "bg-red-500/10 border border-red-500/20 text-red-400"
                  }`}>
                    {passwordMsg.ok ? <CheckCircle className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
                    {passwordMsg.text}
                  </div>
                )}

                <Button
                  type="submit"
                  disabled={changePassword.isPending}
                  className="bg-emerald-600 hover:bg-emerald-500 text-white"
                >
                  {changePassword.isPending ? "Updating…" : "Change Password"}
                </Button>
              </form>
            </CardContent>
          </Card>

          {/* MFA */}
          <Card className="bg-slate-800/50 border-slate-700/50">
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-white">Two-Factor Authentication</CardTitle>
                  <CardDescription className="text-slate-400 mt-1">
                    Add an extra layer of security with a TOTP app
                  </CardDescription>
                </div>
                <Badge
                  className={profile?.mfaEnabled
                    ? "bg-emerald-500/20 text-emerald-400 border-emerald-500/30"
                    : "bg-slate-700 text-slate-400 border-slate-600"}
                >
                  {profile?.mfaEnabled ? "Enabled" : "Disabled"}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {profile?.mfaEnabled ? (
                <div className="space-y-3">
                  <p className="text-sm text-slate-400">
                    To disable MFA, enter the current code from your authenticator app.
                  </p>
                  <div className="flex gap-3">
                    <Input
                      value={disableToken}
                      onChange={(e) => setDisableToken(e.target.value.replace(/\D/g, "").slice(0, 6))}
                      placeholder="000000"
                      maxLength={6}
                      className="w-36 bg-slate-800 border-slate-600 text-white text-center tracking-widest"
                    />
                    <Button
                      variant="destructive"
                      disabled={disableToken.length !== 6 || disableMfa.isPending}
                      onClick={() => disableMfa.mutate(disableToken)}
                    >
                      {disableMfa.isPending ? "Disabling…" : "Disable MFA"}
                    </Button>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <p className="text-sm text-slate-400">
                    MFA is not enabled. Enable it to protect your account with a TOTP authenticator app.
                  </p>
                  <Button
                    onClick={() => window.location.href = "/mfa/setup"}
                    className="bg-emerald-600 hover:bg-emerald-500 text-white"
                  >
                    <Shield className="h-4 w-4 mr-2" />
                    Enable MFA
                  </Button>
                </div>
              )}

              {mfaMsg && (
                <div className={`flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${
                  mfaMsg.ok
                    ? "bg-emerald-500/10 border border-emerald-500/20 text-emerald-400"
                    : "bg-red-500/10 border border-red-500/20 text-red-400"
                }`}>
                  {mfaMsg.ok ? <CheckCircle className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4" />}
                  {mfaMsg.text}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default function SettingsPageWrapper() {
  return (
    <Suspense fallback={null}>
      <SettingsPage />
    </Suspense>
  );
}
