import { useEffect, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Loader2 } from "lucide-react";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

export type EditableUser = {
  user_id: string;
  full_name: string | null;
  email: string;
};

interface EditUserDialogProps {
  user: EditableUser | null;
  onClose: () => void;
  onSaved?: (updated: EditableUser) => void;
}

export const EditUserDialog = ({ user, onClose, onSaved }: EditUserDialogProps) => {
  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");

  useEffect(() => {
    setFullName(user?.full_name ?? "");
    setEmail(user?.email ?? "");
  }, [user]);

  const mut = useMutation({
    mutationFn: async () => {
      if (!user) return;
      const res = await fetch(`/api/admin/users/${user.user_id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ full_name: fullName || null, email }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || `Update failed (${res.status})`);
      }
      return res.json();
    },
    onSuccess: () => {
      toast.success("Account updated");
      if (user) {
        onSaved?.({ user_id: user.user_id, full_name: fullName || null, email });
      }
      onClose();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <Dialog open={!!user} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Edit account</DialogTitle>
        </DialogHeader>
        <div className="space-y-3 mt-2">
          <div>
            <Label htmlFor="edit-name">Full name</Label>
            <Input id="edit-name" value={fullName} onChange={(e) => setFullName(e.target.value)} />
          </div>
          <div>
            <Label htmlFor="edit-email">Email</Label>
            <Input id="edit-email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>Cancel</Button>
          <Button onClick={() => mut.mutate()} disabled={mut.isPending || !email}>
            {mut.isPending && <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />} Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

interface ResetPasswordDialogProps {
  user: EditableUser | null;
  onClose: () => void;
}

export const ResetPasswordDialog = ({ user, onClose }: ResetPasswordDialogProps) => {
  const [pw, setPw] = useState("");
  const [confirm, setConfirm] = useState("");

  useEffect(() => {
    setPw("");
    setConfirm("");
  }, [user]);

  const mut = useMutation({
    mutationFn: async () => {
      if (!user) return;
      const res = await fetch(`/api/admin/users/${user.user_id}/reset-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ password: pw }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || `Reset failed (${res.status})`);
      }
      return res.json();
    },
    onSuccess: () => {
      toast.success("Password reset");
      onClose();
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const valid = pw.length >= 8 && pw === confirm;

  return (
    <Dialog open={!!user} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Set password</DialogTitle>
        </DialogHeader>
        <div className="space-y-3 mt-2">
          <p className="text-xs text-muted-foreground">
            Setting a new password for <strong>{user?.email}</strong>. They will not be notified — share the new password with them yourself.
          </p>
          <div>
            <Label htmlFor="new-pw">New password</Label>
            <Input id="new-pw" type="password" value={pw} onChange={(e) => setPw(e.target.value)} minLength={8} />
            <p className="text-[10px] text-muted-foreground mt-1">Minimum 8 characters.</p>
          </div>
          <div>
            <Label htmlFor="confirm-pw">Confirm password</Label>
            <Input id="confirm-pw" type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} />
            {confirm && confirm !== pw && (
              <p className="text-[10px] text-destructive mt-1">Passwords don't match.</p>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>Cancel</Button>
          <Button onClick={() => mut.mutate()} disabled={!valid || mut.isPending}>
            {mut.isPending && <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />} Set password
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
