'use client';

import { useEffect, useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { OwnerPicker, type OwnerRef } from '@/components/shared/owner-picker';
import { FormErrorSummary } from '@/components/forms/form-error-summary';
import { useFormScrollToError } from '@/hooks/use-form-scroll-to-error';
import { apiFetch } from '@/lib/api/client';

type TransferReason = 'sale' | 'inheritance' | 'gift' | 'company_restructure' | 'other';

type FormValues = {
  newOwner: OwnerRef | undefined;
  effectiveDate: string; // ISO date string from <input type="date">
  transferReason?: TransferReason;
  transferNotes?: string;
};

interface YachtTransferDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  yachtId: string;
  /** Current owner shown for reference; used to guard against selecting the same owner. */
  currentOwner?: OwnerRef;
}

const todayIso = (): string => new Date().toISOString().slice(0, 10);

export function YachtTransferDialog({
  open,
  onOpenChange,
  yachtId,
  currentOwner,
}: YachtTransferDialogProps) {
  const queryClient = useQueryClient();
  const [formError, setFormError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    reset,
    control,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({
    defaultValues: {
      newOwner: undefined,
      effectiveDate: todayIso(),
      transferReason: undefined,
      transferNotes: '',
    },
  });
  const submitWithScroll = useFormScrollToError(handleSubmit, errors);

  useEffect(() => {
    if (open) {
      setFormError(null);
      reset({
        newOwner: undefined,
        effectiveDate: todayIso(),
        transferReason: undefined,
        transferNotes: '',
      });
    }
  }, [open, reset]);

  const newOwner = watch('newOwner');
  const transferReason = watch('transferReason');

  const mutation = useMutation({
    mutationFn: async (data: FormValues) => {
      if (!data.newOwner) {
        throw new Error('Please select a new owner');
      }
      if (
        currentOwner &&
        data.newOwner.type === currentOwner.type &&
        data.newOwner.id === currentOwner.id
      ) {
        throw new Error('New owner must be different from the current owner');
      }
      await apiFetch(`/api/v1/yachts/${yachtId}/transfer`, {
        method: 'POST',
        body: {
          newOwner: data.newOwner,
          effectiveDate: data.effectiveDate,
          transferReason: data.transferReason,
          transferNotes: data.transferNotes?.trim() || undefined,
        },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['yachts', yachtId] });
      queryClient.invalidateQueries({ queryKey: ['yachts', yachtId, 'ownership-history'] });
      queryClient.invalidateQueries({ queryKey: ['yachts'] });
      toast.success('Ownership transferred');
      onOpenChange(false);
    },
    onError: (err: unknown) => {
      const msg = err instanceof Error ? err.message : 'Failed to transfer ownership';
      setFormError(msg);
    },
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Transfer ownership</DialogTitle>
          <DialogDescription>
            This will close the current ownership record and open a new one. The change is logged in
            the audit history.
          </DialogDescription>
        </DialogHeader>

        <form
          onSubmit={submitWithScroll((data) => {
            setFormError(null);
            mutation.mutate(data);
          })}
          className="space-y-4"
        >
          <FormErrorSummary
            errors={errors}
            labels={{
              newOwner: 'New owner',
              effectiveDate: 'Effective date',
              transferReason: 'Reason',
            }}
          />
          <div className="space-y-2">
            <Label>New owner</Label>
            <OwnerPicker
              value={newOwner ?? null}
              onChange={(v) => setValue('newOwner', v ?? undefined)}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="effectiveDate">Effective date</Label>
            <Controller
              control={control}
              name="effectiveDate"
              rules={{ required: true }}
              render={({ field }) => (
                <DatePicker
                  id="effectiveDate"
                  value={field.value ?? ''}
                  onChange={field.onChange}
                />
              )}
            />
            {errors.effectiveDate && <p className="text-xs text-destructive">Required</p>}
          </div>

          <div className="space-y-2">
            <Label>Reason (optional)</Label>
            <Select
              onValueChange={(v) => setValue('transferReason', v as TransferReason)}
              value={transferReason ?? ''}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a reason..." />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="sale">Sale</SelectItem>
                <SelectItem value="inheritance">Inheritance</SelectItem>
                <SelectItem value="gift">Gift</SelectItem>
                <SelectItem value="company_restructure">Company restructure</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="transferNotes">Notes (optional)</Label>
            <Textarea id="transferNotes" rows={3} {...register('transferNotes')} />
          </div>

          {formError && <p className="text-sm text-destructive">{formError}</p>}

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting || mutation.isPending}>
              {(isSubmitting || mutation.isPending) && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
              )}
              Transfer
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
