"use client";

import * as React from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { signOut } from "next-auth/react";

interface MeResponse {
  user: {
    id: string;
    username: string;
    role: string;
  };
}

export function AccountSettings() {
  const qc = useQueryClient();
  const meQuery = useQuery({
    queryKey: ["me"],
    queryFn: () => apiFetch<MeResponse>("/api/me"),
  });

  const [username, setUsername] = React.useState("");
  const [current, setCurrent] = React.useState("");
  const [next, setNext] = React.useState("");
  const [confirm, setConfirm] = React.useState("");

  React.useEffect(() => {
    if (meQuery.data?.user.username) setUsername(meQuery.data.user.username);
  }, [meQuery.data]);

  const renameMutation = useMutation({
    mutationFn: () =>
      apiFetch("/api/me", { method: "PATCH", body: JSON.stringify({ username }) }),
    onSuccess: () => {
      toast.success("Username updated. Sign in again to refresh your session.");
      qc.invalidateQueries({ queryKey: ["me"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const passwordMutation = useMutation({
    mutationFn: () =>
      apiFetch("/api/me", {
        method: "PATCH",
        body: JSON.stringify({ currentPassword: current, newPassword: next }),
      }),
    onSuccess: () => {
      toast.success("Password changed. Please sign in again.");
      setCurrent("");
      setNext("");
      setConfirm("");
      setTimeout(() => signOut({ callbackUrl: "/login" }), 800);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Username</CardTitle>
          <CardDescription>Your sign-in identifier.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="space-y-1.5">
            <Label>Username</Label>
            <Input value={username} onChange={(e) => setUsername(e.target.value)} />
          </div>
          <div className="flex justify-end">
            <Button
              onClick={() => renameMutation.mutate()}
              disabled={renameMutation.isPending || !username || username === meQuery.data?.user.username}
            >
              {renameMutation.isPending ? "Saving…" : "Save"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Change password</CardTitle>
          <CardDescription>You will be signed out after changing.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="space-y-1.5">
            <Label>Current password</Label>
            <Input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label>New password</Label>
            <Input type="password" value={next} onChange={(e) => setNext(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label>Confirm new password</Label>
            <Input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} />
          </div>
          <div className="flex justify-end">
            <Button
              onClick={() => {
                if (next !== confirm) {
                  toast.error("Passwords do not match");
                  return;
                }
                if (next.length < 6) {
                  toast.error("Password must be at least 6 characters");
                  return;
                }
                passwordMutation.mutate();
              }}
              disabled={passwordMutation.isPending || !current || !next || !confirm}
            >
              {passwordMutation.isPending ? "Changing…" : "Change password"}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
