'use client';

import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';
import { PIPELINE_STAGES } from '@/lib/constants';

const STAGE_LABELS: Record<string, string> = {
  open: 'Open',
  details_sent: 'Details Sent',
  in_communication: 'In Communication',
  visited: 'Visited',
  signed_eoi_nda: 'Signed EOI/NDA',
  deposit_10pct: 'Deposit 10%',
  contract: 'Contract',
  completed: 'Completed',
};

interface InterestStagePickerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  interestId: string;
  currentStage: string;
}

export function InterestStagePicker({
  open,
  onOpenChange,
  interestId,
  currentStage,
}: InterestStagePickerProps) {
  const queryClient = useQueryClient();
  const [newStage, setNewStage] = useState<string>(currentStage);
  const [reason, setReason] = useState('');

  const mutation = useMutation({
    mutationFn: () =>
      apiFetch(`/api/v1/interests/${interestId}/stage`, {
        method: 'PATCH',
        body: { pipelineStage: newStage, reason: reason || undefined },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['interests', interestId] });
      queryClient.invalidateQueries({ queryKey: ['interests'] });
      onOpenChange(false);
      setReason('');
    },
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Change Stage</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="space-y-1">
            <Label>Current Stage</Label>
            <p className="text-sm text-muted-foreground">
              {STAGE_LABELS[currentStage] ?? currentStage}
            </p>
          </div>

          <div className="space-y-1">
            <Label>New Stage</Label>
            <Select value={newStage} onValueChange={setNewStage}>
              <SelectTrigger>
                <SelectValue placeholder="Select new stage" />
              </SelectTrigger>
              <SelectContent>
                {PIPELINE_STAGES.map((s) => (
                  <SelectItem key={s} value={s}>
                    {STAGE_LABELS[s] ?? s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-1">
            <Label>Reason (optional)</Label>
            <Textarea
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Reason for stage change..."
              rows={2}
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={mutation.isPending}
          >
            Cancel
          </Button>
          <Button
            onClick={() => mutation.mutate()}
            disabled={mutation.isPending || newStage === currentStage}
          >
            {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Confirm
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
