'use client';

import { useState, useMemo } from 'react';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/shared/components/ui/dialog';
import { Button } from '@/shared/components/ui/button';
import { Label } from '@/shared/components/ui/label';
import { Textarea } from '@/shared/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/components/ui/select';
import type { TrackedDeadline, DeadlineResolution } from '../types';
import { getDeadlineType } from '../services/deadline-catalog';

interface DeadlineResolveDialogProps {
  open: boolean;
  deadline: TrackedDeadline | null;
  onOpenChange: (open: boolean) => void;
  onResolve: (resolution: DeadlineResolution, note: string, chainNext: boolean) => void;
}

const ALL_RESOLUTION_OPTIONS: Array<{ value: DeadlineResolution; label: string }> = [
  { value: 'completed', label: 'Finalizat' },
  { value: 'aprobat-tacit', label: 'Aprobat tacit' },
  { value: 'intrerupt', label: 'Intrerupt (completari solicitate)' },
  { value: 'respins', label: 'Respins' },
  { value: 'anulat', label: 'Anulat' },
];

export function DeadlineResolveDialog({ open, deadline, onOpenChange, onResolve }: DeadlineResolveDialogProps) {
  const [resolution, setResolution] = useState<DeadlineResolution>('completed');
  const [note, setNote] = useState('');

  const def = deadline ? getDeadlineType(deadline.typeId) : undefined;

  // "intrerupt" option only for avize deadlines that have a chain (interruption mechanism)
  const filteredOptions = useMemo(() => {
    return ALL_RESOLUTION_OPTIONS.filter((opt) => {
      if (opt.value === 'intrerupt') {
        return def?.chainNextTypeId && def?.category === 'avize';
      }
      return true;
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [def?.chainNextTypeId, def?.category]);

  if (!deadline) return null;

  // Chain fires on completed, aprobat-tacit, or intrerupt (for avize interruption)
  const hasChain = def?.chainNextTypeId && (
    resolution === 'completed' || resolution === 'aprobat-tacit' || resolution === 'intrerupt'
  );

  const handleResolve = () => {
    onResolve(resolution, note, !!hasChain);
    setResolution('completed');
    setNote('');
    onOpenChange(false);
  };

  const handleClose = () => {
    setResolution('completed');
    setNote('');
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={(o) => { if (!o) handleClose(); }}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Rezolva — {def?.label ?? deadline.typeId}</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div>
            <Label>Rezolutie</Label>
            <Select value={resolution} onValueChange={(v) => setResolution(v as DeadlineResolution)}>
              <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
              <SelectContent>
                {filteredOptions.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>Nota (optional)</Label>
            <Textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={2}
              className="mt-1"
              placeholder="Detalii rezolutie..."
            />
          </div>

          {hasChain && resolution !== 'intrerupt' && def?.chainNextActionLabel && (
            <div className="rounded-lg border border-blue-500/30 bg-blue-50 dark:bg-blue-950/20 p-3">
              <p className="text-sm font-medium text-blue-800 dark:text-blue-200">
                Termen inlantuit disponibil
              </p>
              <p className="text-xs text-blue-700 dark:text-blue-300 mt-1">
                La rezolvare se va crea automat: {def.chainNextActionLabel}
              </p>
            </div>
          )}

          {resolution === 'intrerupt' && def?.chainNextTypeId && (
            <div className="rounded-lg border border-amber-500/30 bg-amber-50 dark:bg-amber-950/20 p-3">
              <p className="text-sm font-medium text-amber-800 dark:text-amber-200">
                Termen intrerupt — completari solicitate
              </p>
              <p className="text-xs text-amber-700 dark:text-amber-300 mt-1">
                Termenul initial se intrerupe. Se va crea automat un nou termen de 15 zile
                calendaristice care incepe de la data depunerii completarilor. Actualizati
                data start cand completarile sunt depuse.
              </p>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={handleClose}>Anuleaza</Button>
          <Button type="button" onClick={handleResolve}>Rezolva</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
