'use client';

import { useState } from 'react';
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 { DatePicker } from '@/components/ui/date-picker';
import { Textarea } from '@/components/ui/textarea';
import { ClientPicker } from '@/components/shared/client-picker';
import { YachtPicker } from '@/components/yachts/yacht-picker';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface TenancyTransferDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tenancyId: string;
}

export function TenancyTransferDialog(props: TenancyTransferDialogProps) {
  return props.open ? <Inner {...props} key={String(props.open)} /> : null;
}

function Inner({ open, onOpenChange, tenancyId }: TenancyTransferDialogProps) {
  const qc = useQueryClient();
  const [newClientId, setNewClientId] = useState<string | null>(null);
  const [newYachtId, setNewYachtId] = useState<string | null>(null);
  const [transferDate, setTransferDate] = useState(new Date().toISOString().slice(0, 10));
  const [notes, setNotes] = useState('');

  const mutation = useMutation({
    mutationFn: async () => {
      if (!newClientId) throw new Error('Pick a new client');
      if (!newYachtId) throw new Error('Pick a new yacht');
      return apiFetch(`/api/v1/tenancies/${tenancyId}/transfer`, {
        method: 'POST',
        body: {
          newClientId,
          newYachtId,
          transferDate,
          ...(notes.trim() ? { notes: notes.trim() } : {}),
        },
      });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenancy', tenancyId] });
      qc.invalidateQueries({ queryKey: ['tenancies'] });
      toast.success('Tenancy transferred');
      onOpenChange(false);
    },
    onError: (err) => toastError(err),
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Transfer tenancy</DialogTitle>
          <DialogDescription>
            Hand this berth to a new client + yacht. The current tenancy is ended at the transfer
            date; a new active row is created with transferredFromTenancyId pointing back.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label>New client</Label>
            <ClientPicker value={newClientId} onChange={setNewClientId} />
          </div>
          <div className="space-y-1.5">
            <Label>New yacht</Label>
            <YachtPicker
              value={newYachtId}
              onChange={setNewYachtId}
              ownerFilter={newClientId ? { type: 'client', id: newClientId } : undefined}
              disabled={!newClientId}
              placeholder={newClientId ? 'Select yacht...' : 'Pick a client first'}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="transfer-date">Transfer date</Label>
            <DatePicker id="transfer-date" value={transferDate} onChange={setTransferDate} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="transfer-notes">Notes (optional)</Label>
            <Textarea
              id="transfer-notes"
              rows={2}
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
            />
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type="button" onClick={() => mutation.mutate()} disabled={mutation.isPending}>
            {mutation.isPending && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" aria-hidden />}
            Transfer
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
