'use client';

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

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 { toastError } from '@/lib/api/toast-error';
import { usePermissions } from '@/hooks/use-permissions';
import { PIPELINE_STAGES, STAGE_LABELS, stageLabel, canTransitionStage } from '@/lib/constants';

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

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

  // The transition table allows reasonable forward jumps; rejecting a
  // proposed stage flips the UI into "override" mode if the user has
  // permission to skip the rules.
  const transitionAllowed = newStage === currentStage || canTransitionStage(currentStage, newStage);
  const canOverride = isSuperAdmin || can('interests', 'override_stage');
  const overrideRequired = !transitionAllowed;
  const overrideEffective = override || overrideRequired;
  const reasonRequiredByOverride = overrideEffective;
  const reasonValid = !reasonRequiredByOverride || reason.trim().length >= 5;

  const mutation = useMutation({
    mutationFn: () =>
      apiFetch(`/api/v1/interests/${interestId}/stage`, {
        method: 'PATCH',
        body: {
          pipelineStage: newStage,
          reason: reason || undefined,
          override: overrideEffective || undefined,
        },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['interests', interestId] });
      queryClient.invalidateQueries({ queryKey: ['interests'] });
      onOpenChange(false);
      setReason('');
      setOverride(false);
      toast.success(overrideEffective ? 'Stage overridden' : 'Stage updated');
    },
    onError: (err: unknown) => {
      toastError(err, 'Stage change failed');
    },
  });

  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">{stageLabel(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]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {overrideRequired && (
            <div
              className={`flex items-start gap-2 rounded-md border p-3 text-xs ${
                canOverride
                  ? 'border-amber-300 bg-amber-50 text-amber-900'
                  : 'border-red-300 bg-red-50 text-red-900'
              }`}
            >
              <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" aria-hidden />
              {canOverride ? (
                <span>
                  This is not a normal forward transition. Override is enabled - supply a reason
                  below explaining the manual stage change. Recorded in the audit log.
                </span>
              ) : (
                <span>
                  This stage transition isn&rsquo;t allowed by the pipeline rules. You don&rsquo;t
                  have permission to override.
                </span>
              )}
            </div>
          )}

          {transitionAllowed && canOverride && newStage !== currentStage && (
            <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
              <input
                type="checkbox"
                checked={override}
                onChange={(e) => setOverride(e.target.checked)}
              />
              Force-override (skip transition rules) - requires a reason
            </label>
          )}

          <div className="space-y-1">
            <Label>
              Reason {reasonRequiredByOverride && <span className="text-red-600">*</span>}
            </Label>
            <Textarea
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder={
                reasonRequiredByOverride
                  ? 'Required: why is this stage being overridden? (min 5 chars)'
                  : 'Optional: 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 ||
              (overrideRequired && !canOverride) ||
              !reasonValid
            }
          >
            {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />}
            {overrideEffective ? 'Override stage' : 'Confirm'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
