import { useState } from 'react';

import { useForm } from '@inertiajs/react';

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/Components/ui/alert-dialog';
import { Button } from '@/Components/ui/button';
import { ErrorMessage } from '@/Components/ui/error-message';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';

export default function DeleteUserForm() {
  const [open, setOpen] = useState(false);
  const { data, setData, delete: destroy, processing, errors, reset } = useForm({
    password: '',
  });

  const handleDelete = (e: React.FormEvent) => {
    e.preventDefault();
    destroy(route('profile.destroy'), {
      onSuccess: () => {
        setOpen(false);
        reset();
      },
    });
  };

  return (
    <>
      <Button variant="destructive" onClick={() => setOpen(true)}>
        Delete Account
      </Button>

      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Account</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. Please enter your password to confirm account
              deletion. All your data will be permanently removed.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <form onSubmit={handleDelete} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                value={data.password}
                onChange={(e) => setData('password', e.target.value)}
                disabled={processing}
                autoComplete="current-password"
                placeholder="Enter your password"
              />
              <ErrorMessage error={errors.password} variant="inline" />
            </div>

            <div className="flex gap-3 justify-end">
              <AlertDialogCancel disabled={processing}>Cancel</AlertDialogCancel>
              <AlertDialogAction
                asChild
                disabled={processing || !data.password}
              >
                <Button
                  type="submit"
                  variant="destructive"
                  disabled={processing || !data.password}
                >
                  {processing ? 'Deleting...' : 'Delete Account'}
                </Button>
              </AlertDialogAction>
            </div>
          </form>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
