"use client";

/**
 * Status Monitor Config — Dialog for activating external status monitoring.
 *
 * Shows when a recipient matches a known authority and registration number
 * is filled. Lets user confirm/set petitioner name and activates monitoring.
 */

import { useState, useEffect } from "react";
import { Radio } from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import type { RegistryEntry, ExternalStatusTracking } from "../types";
import type { AuthorityConfig } from "../services/authority-catalog";

interface StatusMonitorConfigProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  entry: RegistryEntry;
  authority: AuthorityConfig;
  onActivate: (tracking: ExternalStatusTracking) => void;
  /** When true, pre-fills from existing tracking data for editing */
  editMode?: boolean;
}

export function StatusMonitorConfig({
  open,
  onOpenChange,
  entry,
  authority,
  onActivate,
  editMode,
}: StatusMonitorConfigProps) {
  const existing = entry.externalStatusTracking;
  const [petitionerName, setPetitionerName] = useState("");
  const [regNumber, setRegNumber] = useState(
    entry.recipientRegNumber ?? "",
  );
  const [regDate, setRegDate] = useState("");

  // Pre-fill: edit mode uses existing tracking, otherwise entry fields
  useEffect(() => {
    if (editMode && existing) {
      setPetitionerName(existing.petitionerName);
      setRegNumber(existing.regNumber);
      setRegDate(existing.regDate);
    } else {
      setRegNumber(entry.recipientRegNumber ?? "");
      if (entry.recipientRegDate) {
        const parts = entry.recipientRegDate.split("-");
        if (parts.length === 3) {
          setRegDate(`${parts[2]}.${parts[1]}.${parts[0]}`);
        }
      }
      const saved = localStorage.getItem(
        `status-monitor-petitioner:${authority.id}`,
      );
      if (saved) setPetitionerName(saved);
    }
  }, [editMode, existing, entry.recipientRegNumber, entry.recipientRegDate, authority.id]);

  const canActivate =
    petitionerName.trim().length >= 3 &&
    regNumber.trim().length > 0 &&
    regDate.trim().length > 0;

  const handleActivate = () => {
    // Save petitioner name for future use
    localStorage.setItem(
      `status-monitor-petitioner:${authority.id}`,
      petitionerName.trim(),
    );

    const tracking: ExternalStatusTracking = editMode && existing
      ? {
          ...existing,
          petitionerName: petitionerName.trim(),
          regNumber: regNumber.trim(),
          regDate: regDate.trim(),
          active: true,
          lastError: null,
        }
      : {
          authorityId: authority.id,
          petitionerName: petitionerName.trim(),
          regNumber: regNumber.trim(),
          regDate: regDate.trim(),
          lastCheckAt: null,
          lastStatusRow: null,
          statusHash: "",
          semanticStatus: "necunoscut",
          history: [],
          active: true,
          lastError: null,
        };

    onActivate(tracking);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Radio className="h-4 w-4" />
            {editMode ? "Modifica monitorizarea" : "Monitorizare status extern"}
          </DialogTitle>
          <DialogDescription>
            {editMode
              ? "Modifica datele de monitorizare. Istoricul se pastreaza."
              : `${authority.name} suporta verificarea automata a statusului. Configureaza datele de mai jos pentru a activa monitorizarea.`}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 py-2">
          <div className="space-y-1.5">
            <Label htmlFor="petitioner-name">
              Nume deponent (cum apare la autoritate)
            </Label>
            <Input
              id="petitioner-name"
              value={petitionerName}
              onChange={(e) => setPetitionerName(e.target.value)}
              placeholder="ex: BELETAGE SRL"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="reg-number">Nr. inregistrare</Label>
              <Input
                id="reg-number"
                value={regNumber}
                onChange={(e) => setRegNumber(e.target.value)}
                placeholder="ex: 12345"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="reg-date">Data inregistrare (zz.ll.aaaa)</Label>
              <Input
                id="reg-date"
                value={regDate}
                onChange={(e) => setRegDate(e.target.value)}
                placeholder="ex: 11.03.2026"
              />
            </div>
          </div>

          <p className="text-[10px] text-muted-foreground">
            Verificarea se face automat de 4 ori pe zi (9:00, 12:00, 15:00,
            17:00) in zilele lucratoare. Poti verifica manual oricand din
            panoul de detalii.
          </p>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Anuleaza
          </Button>
          <Button onClick={handleActivate} disabled={!canActivate}>
            {editMode ? "Salveaza" : "Activeaza monitorizarea"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
