'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 { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

const PERMANENT = new Set(['permanent', 'fee_simple', 'strata_lot']);

interface TenancyRenewDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tenancyId: string;
  tenureType: string;
  currentEndDate: string | Date | null;
}

function toIso(d: string | Date | null | undefined): string {
  if (!d) return '';
  return (d instanceof Date ? d : new Date(d)).toISOString().slice(0, 10);
}

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

function Inner({
  open,
  onOpenChange,
  tenancyId,
  tenureType,
  currentEndDate,
}: TenancyRenewDialogProps) {
  const qc = useQueryClient();
  const today = new Date();
  const isPermanent = PERMANENT.has(tenureType);
  const [newStartDate, setNewStartDate] = useState(toIso(currentEndDate ?? today));
  const [newEndDate, setNewEndDate] = useState('');
  const [notes, setNotes] = useState('');

  const mutation = useMutation({
    mutationFn: async () => {
      return apiFetch(`/api/v1/tenancies/${tenancyId}/renew`, {
        method: 'POST',
        body: {
          newStartDate,
          ...(newEndDate ? { newEndDate } : {}),
          ...(notes.trim() ? { notes: notes.trim() } : {}),
        },
      });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenancy', tenancyId] });
      qc.invalidateQueries({ queryKey: ['tenancies'] });
      toast.success(isPermanent ? 'Tenancy renewed in place' : 'Renewal created');
      onOpenChange(false);
    },
    onError: (err) => toastError(err),
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Renew tenancy</DialogTitle>
          <DialogDescription>
            {isPermanent
              ? 'Permanent tenancies are renewed in place — start and end dates update on the existing row.'
              : 'A new tenancy row will be minted with previousTenancyId pointing to this one. The current row is ended at its existing end date.'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="renew-start">New start date</Label>
            <DatePicker id="renew-start" value={newStartDate} onChange={setNewStartDate} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="renew-end">
              New end date
              {isPermanent ? (
                <span className="ml-1 text-xs font-normal text-muted-foreground">(optional)</span>
              ) : (
                <span className="ml-1 text-xs font-normal text-destructive">(required)</span>
              )}
            </Label>
            <DatePicker id="renew-end" value={newEndDate} onChange={setNewEndDate} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="renew-notes">Notes (optional)</Label>
            <Textarea
              id="renew-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 />}
            Renew
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
