import { KeyRound } from 'lucide-react';
import React from 'react';

import { changePassword } from '@/actions/App/Domains/Shared/Http/Controllers/Admin/UserController';

import PasswordInput from '@/components/PasswordInput';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { useYupForm } from '@/hooks/use-yup-form';
import { PASSWORD_HINT } from '@/lib/field-constraints';
import { userPasswordSchema } from '@/lib/validation/user';
import type { AdminUser } from '@/types/admin';

interface UserPasswordDialogProps {
    user: AdminUser | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

export function UserPasswordDialog({
    user,
    open,
    onOpenChange,
}: UserPasswordDialogProps) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-110 [&>button:last-child]:hidden">
                {user && (
                    <UserPasswordForm
                        key={user.id}
                        user={user}
                        onClose={() => onOpenChange(false)}
                    />
                )}
            </DialogContent>
        </Dialog>
    );
}

function UserPasswordForm({
    user,
    onClose,
}: {
    user: AdminUser;
    onClose: () => void;
}) {
    const { data, setData, processing, errors, reset, validateField, submit } =
        useYupForm(userPasswordSchema, {
            password: '',
            password_confirmation: '',
        });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        submit((form) =>
            form.put(changePassword({ user: user.id }).url, {
                preserveScroll: true,
                onSuccess: () => {
                    reset();
                    onClose();
                },
            }),
        );
    };

    return (
        <>
            <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                    <KeyRound className="h-5 w-5" />
                    Change Password
                </DialogTitle>
                <DialogDescription>
                    Set a temporary password for{' '}
                    <span className="font-medium text-foreground">
                        {user.name}
                    </span>
                    . They will be asked to change it on their next login.
                </DialogDescription>
            </DialogHeader>

            <form onSubmit={handleSubmit} className="space-y-4 py-4" noValidate>
                <div className="space-y-2">
                    <Label htmlFor="new-user-password">New Password</Label>
                    <PasswordInput
                        id="new-user-password"
                        autoComplete="new-password"
                        value={data.password}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setData('password', e.target.value)
                        }
                        onBlur={() => validateField('password')}
                        required
                    />
                    <p className="text-xs text-muted-foreground">
                        {PASSWORD_HINT}
                    </p>
                    {errors.password && (
                        <p className="text-xs text-destructive">
                            {errors.password}
                        </p>
                    )}
                </div>

                <div className="space-y-2">
                    <Label htmlFor="new-user-password-confirmation">
                        Confirm Password
                    </Label>
                    <PasswordInput
                        id="new-user-password-confirmation"
                        autoComplete="new-password"
                        value={data.password_confirmation}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            setData('password_confirmation', e.target.value)
                        }
                        onBlur={() => validateField('password_confirmation')}
                        required
                    />
                    {errors.password_confirmation && (
                        <p className="text-xs text-destructive">
                            {errors.password_confirmation}
                        </p>
                    )}
                </div>

                <DialogFooter className="pt-4">
                    <Button type="button" variant="outline" onClick={onClose}>
                        Cancel
                    </Button>
                    <Button type="submit" disabled={processing}>
                        {processing ? 'Saving...' : 'Change Password'}
                    </Button>
                </DialogFooter>
            </form>
        </>
    );
}
