import { useQuery, useMutation } from "@tanstack/react-query";
import { client } from "@/client";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Shield, ShieldOff, Mail } from "lucide-react";

function TwoFactorSection() {
  const { data: status, isLoading } = useQuery({
    queryKey: ["auth", "2fa", "status"],
    queryFn: async () => {
      const res = await client.authStatus2fa();
      return res.data;
    },
    retry: false,
  });

  const enable2fa = useMutation({
    mutationFn: async () => {
      const res = await client.authEnable2fa();
      return res.data;
    },
  });

  if (isLoading) {
    return <div className="h-16 animate-pulse rounded-lg bg-muted" />;
  }

  if (status?.is_enabled) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="size-4 text-success" />
            Two-factor authentication enabled
          </CardTitle>
          <CardDescription>Your account is protected with 2FA</CardDescription>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            Method: {status.method ?? "TOTP"}
            {status.has_backup_codes ? " — Backup codes available" : " — No backup codes"}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <ShieldOff className="size-4 text-warning" />
          Two-factor authentication
        </CardTitle>
        <CardDescription>Add an extra layer of security to your account</CardDescription>
      </CardHeader>
      <CardContent>
        {enable2fa.data ? (
          <div className="space-y-4">
            <p className="text-sm text-foreground font-medium">
              Scan this QR code with your authenticator app, then enter the code below to verify.
            </p>
            <img alt="2FA QR code" className="size-48 rounded-lg border border-border" src={enable2fa.data.qr_code} />
            <p className="font-mono text-xs text-muted-foreground">Secret: {enable2fa.data.secret}</p>
            <div className="space-y-2">
              <p className="font-heading font-medium text-sm text-foreground">Backup codes (save these!)</p>
              <div className="grid grid-cols-2 gap-1">
                {enable2fa.data.backup_codes.map((code) => (
                  <p className="font-mono text-xs text-muted-foreground" key={code}>{code}</p>
                ))}
              </div>
            </div>
          </div>
        ) : (
          <Button onClick={() => enable2fa.mutate()}>
            Enable 2FA
          </Button>
        )}
      </CardContent>
    </Card>
  );
}

function EmailSection() {
  const { data: emailData, isLoading } = useQuery({
    queryKey: ["auth", "email"],
    queryFn: async () => {
      const res = await client.authGetEmail();
      return res.data;
    },
    retry: false,
  });

  const changeEmail = useMutation({
    mutationFn: async (data: { new_email: string; password: string }) => {
      await client.authEmailChangeRequest(data);
    },
  });

  if (isLoading) {
    return <div className="h-16 animate-pulse rounded-lg bg-muted" />;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Mail className="size-4" />
          Email address
        </CardTitle>
        <CardDescription>Your email is used for notifications and account recovery</CardDescription>
      </CardHeader>
      <CardContent>
        <p className="font-mono text-sm text-foreground">{emailData?.email ?? "Not set"}</p>
        {changeEmail.isIdle && (
          <form
            className="mt-4 space-y-3"
            onSubmit={(e) => {
              e.preventDefault();
              const fd = new FormData(e.currentTarget);
              changeEmail.mutate({
                new_email: fd.get("new_email") as string,
                password: fd.get("password") as string,
              });
            }}
          >
            <div>
              <Label>New email</Label>
              <Input className="mt-1 h-9" name="new_email" placeholder="new@email.com" required type="email" />
            </div>
            <div>
              <Label>Current password</Label>
              <Input className="mt-1 h-9" name="password" placeholder="Confirm password" required type="password" />
            </div>
            <Button size="sm" type="submit">Change email</Button>
          </form>
        )}
        {changeEmail.isSuccess && (
          <p className="mt-4 text-sm text-success">Verification email sent. Check your inbox.</p>
        )}
        {changeEmail.isError && (
          <p className="mt-4 text-sm text-destructive">Failed to change email. Please try again.</p>
        )}
      </CardContent>
    </Card>
  );
}

export default function SettingsSecurityPage() {
  return (
    <div className="px-8 py-10">
      <h1 className="text-xl font-heading font-bold text-foreground">Security</h1>
      <p className="mt-1 text-sm text-muted-foreground">Manage your account security, 2FA, and credentials</p>

      <div className="mt-8 space-y-6">
        <TwoFactorSection />
        <EmailSection />
      </div>
    </div>
  );
}