'use client';

import { AlertTriangle, HelpCircle } from 'lucide-react';
import { useId, type ReactNode } from 'react';

import { FieldError, FormAlert } from '@/components/forms/form-field';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/input';
import { Modal } from '@/components/ui/overlay';
import { cn } from '@/lib/utils';

/** Confirm dialog that requires a written reason (suspend, reject, adjust). */
export function ReasonDialog({
  open,
  title,
  message,
  reason,
  onReasonChange,
  reasonLabel = 'Reason',
  reasonError,
  confirmLabel,
  cancelLabel = 'Cancel',
  destructive = true,
  loading = false,
  error,
  children,
  onConfirm,
  onClose,
}: {
  open: boolean;
  title: string;
  message: ReactNode;
  reason: string;
  onReasonChange: (reason: string) => void;
  reasonLabel?: string;
  reasonError?: string | null;
  confirmLabel: string;
  cancelLabel?: string;
  destructive?: boolean;
  loading?: boolean;
  error?: string | null;
  children?: ReactNode;
  onConfirm: () => void;
  onClose: () => void;
}) {
  const id = useId();
  const Icon = destructive ? AlertTriangle : HelpCircle;
  return (
    <Modal open={open} title={title} onClose={onClose}>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          onConfirm();
        }}
      >
        <div className="flex items-start gap-4">
          <span className={cn('grid h-10 w-10 shrink-0 place-items-center rounded-full', destructive ? 'bg-danger-soft text-danger' : 'bg-primary-soft text-primary')} aria-hidden="true">
            <Icon className="h-5 w-5" />
          </span>
          <div className="min-w-0 flex-1 pt-2 text-body text-muted-foreground">{message}</div>
        </div>
        {children}
        <div className="mt-4 grid gap-1.5">
          <label htmlFor={id} className="text-small font-semibold">
            {reasonLabel}
          </label>
          <Textarea id={id} value={reason} aria-invalid={reasonError ? true : undefined} className="min-h-24" onChange={(event) => onReasonChange(event.target.value)} />
          {reasonError ? <FieldError id={`${id}-error`}>{reasonError}</FieldError> : null}
        </div>
        {error === undefined || error === null ? null : <FormAlert className="mt-4">{error}</FormAlert>}
        <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
          <Button type="button" variant="secondary" onClick={onClose} disabled={loading}>
            {cancelLabel}
          </Button>
          <Button type="submit" variant={destructive ? 'destructive' : 'primary'} loading={loading}>
            {confirmLabel}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
