'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

type TenureType = 'permanent' | 'fixed_term' | 'seasonal';

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

interface TenancyEditDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tenancyId: string;
  initialStartDate: string | Date;
  initialEndDate: string | Date | null;
  initialTenureType: string;
  initialNotes: string | null;
}

/**
 * Edit non-status metadata on a tenancy (start/end dates, tenure type,
 * notes). Status transitions go through the activate / end / cancel
 * actions on the [id] PATCH route; this dialog only touches metadata.
 */
/**
 * Outer wrapper: forces a fresh mount whenever the dialog opens, so the
 * inner form re-initialises from the current row data without a
 * setState-in-effect. Closed dialog stays unmounted so the form holds
 * no stale state between opens.
 */
export function TenancyEditDialog(props: TenancyEditDialogProps) {
  return props.open ? <TenancyEditDialogInner {...props} key={String(props.open)} /> : null;
}

function TenancyEditDialogInner({
  open,
  onOpenChange,
  tenancyId,
  initialStartDate,
  initialEndDate,
  initialTenureType,
  initialNotes,
}: TenancyEditDialogProps) {
  const qc = useQueryClient();
  const [startDate, setStartDate] = useState(toIsoDate(initialStartDate));
  const [endDate, setEndDate] = useState(toIsoDate(initialEndDate));
  const [tenureType, setTenureType] = useState<TenureType>(initialTenureType as TenureType);
  const [notes, setNotes] = useState(initialNotes ?? '');

  const mutation = useMutation({
    mutationFn: async () => {
      return apiFetch(`/api/v1/tenancies/${tenancyId}`, {
        method: 'PATCH',
        body: {
          action: 'update',
          startDate,
          endDate: endDate || null,
          tenureType,
          notes: notes.trim() || null,
        },
      });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tenancy', tenancyId] });
      qc.invalidateQueries({ queryKey: ['tenancies'] });
      toast.success('Tenancy updated');
      onOpenChange(false);
    },
    onError: (err) => toastError(err),
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Edit tenancy</DialogTitle>
          <DialogDescription>
            Adjust dates, tenure, or notes. Status transitions (activate / end / cancel) live in the
            detail page actions.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="edit-start-date">Start date</Label>
            <DatePicker id="edit-start-date" value={startDate} onChange={setStartDate} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="edit-end-date">
              End date <span className="text-xs font-normal text-muted-foreground">(optional)</span>
            </Label>
            <DatePicker id="edit-end-date" value={endDate} onChange={setEndDate} />
          </div>
          <div className="space-y-1.5">
            <Label>Tenure</Label>
            <Select value={tenureType} onValueChange={(v) => setTenureType(v as TenureType)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="permanent">Permanent</SelectItem>
                <SelectItem value="fixed_term">Fixed term</SelectItem>
                <SelectItem value="seasonal">Seasonal</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="edit-notes">Notes</Label>
            <Textarea
              id="edit-notes"
              rows={3}
              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 />}
            Save changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
