import { Button, Input, Label, Modal } from '@/Components/ui';
import { useState } from 'react';
import { jsonHeaders, type KitRow } from './shared';

/**
 * Type-the-kit-key-to-confirm delete dialog. Shared by Index list-row +
 * Show page header. DELETE /admin/kits/{key} with a confirm_key body for
 * server-side double-check.
 */
export function DeleteModal({
    kit,
    onClose,
    onDeleted,
}: {
    kit: KitRow;
    onClose: () => void;
    onDeleted: () => void;
}) {
    const [confirmKey, setConfirmKey] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const matches = confirmKey === kit.key;

    const submit = async () => {
        if (!matches || submitting) return;
        setSubmitting(true);
        setError(null);
        try {
            const res = await fetch(`/admin/kits/${encodeURIComponent(kit.key)}`, {
                method: 'DELETE',
                credentials: 'same-origin',
                headers: jsonHeaders(),
                body: JSON.stringify({ confirm_key: kit.key }),
            });
            if (!res.ok && res.status !== 204) {
                const body = (await res.json().catch(() => null)) as {
                    message?: string;
                } | null;
                setError(body?.message ?? `Delete failed (${res.status}).`);
                return;
            }
            onDeleted();
        } catch {
            setError('Network error. Try again.');
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Modal
            open
            onClose={onClose}
            size="md"
            onSubmit={(e) => {
                e.preventDefault();
                submit();
            }}
            closeOnBackdrop={false}
            closeOnEsc={!submitting}
            data-testid="admin-kits-delete-modal"
            aria-labelledby="admin-kits-delete-title"
        >
            <Modal.Header
                eyebrow="Delete kit"
                eyebrowClassName="text-destructive"
                titleId="admin-kits-delete-title"
                title={<>Delete &ldquo;{kit.name}&rdquo;?</>}
            />
            <Modal.Body fade={false}>
                <p className="text-sm text-muted-foreground">
                    This will remove the kit's files + marketing previews.
                    This cannot be undone. Existing projects that were
                    scaffolded from this kit aren't affected — they own
                    copies of the assets.
                </p>

                <div>
                    <Label htmlFor="admin-kits-delete-confirm-input">
                        Type the kit key{' '}
                        <span className="font-mono text-[11px] text-foreground/80">
                            {kit.key}
                        </span>{' '}
                        to confirm
                    </Label>
                    <Input
                        id="admin-kits-delete-confirm-input"
                        value={confirmKey}
                        onChange={(e) => setConfirmKey(e.target.value)}
                        placeholder={kit.key}
                        className="mt-1 font-mono"
                        disabled={submitting}
                        autoFocus
                        data-testid="admin-kits-delete-confirm-input"
                    />
                </div>

                {error && (
                    <p
                        className="text-xs text-destructive"
                        role="alert"
                        data-testid="admin-kits-delete-error"
                    >
                        {error}
                    </p>
                )}
            </Modal.Body>
            <Modal.Footer>
                <Button
                    type="button"
                    variant="ghost"
                    onClick={onClose}
                    disabled={submitting}
                >
                    Cancel
                </Button>
                <Button
                    type="button"
                    variant="danger"
                    onClick={submit}
                    disabled={!matches || submitting}
                    data-testid="admin-kits-delete-confirm"
                >
                    {submitting ? 'Deleting…' : 'Delete kit'}
                </Button>
            </Modal.Footer>
        </Modal>
    );
}
