import { useEffect } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Plus, Trash2 } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { RoutingRule } from "@/types/api";
import type { PolicyPayload } from "@/api/policies";

const conditionSchema = z.object({
  field: z.string().min(1, "Champ requis"),
  operator: z.string().min(1, "Opérateur requis"),
  value: z.string().min(1, "Valeur requise"),
});

const policySchema = z.object({
  name: z.string().min(1, "Le nom est requis"),
  description: z.string(),
  priority: z.coerce.number().int().min(1).max(1000),
  is_enabled: z.boolean(),
  conditions: z.array(conditionSchema),
  action: z.object({
    provider: z.string().min(1, "Le fournisseur est requis"),
    model: z.string().min(1, "Le modèle est requis"),
    fallback_chain: z.array(z.string()).optional(),
  }),
});

type PolicyFormData = z.infer<typeof policySchema>;

const PROVIDERS = ["openai", "anthropic", "azure", "mistral", "ollama"];
const CONDITION_FIELDS = ["department", "user_role", "model", "sensitivity_level", "tenant_id"];
const CONDITION_OPERATORS = ["eq", "neq", "in", "prefix"];

interface PolicyFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  rule?: RoutingRule;
  onSubmit: (payload: PolicyPayload) => void;
  isPending: boolean;
}

export function PolicyForm({ open, onOpenChange, rule, onSubmit, isPending }: PolicyFormProps) {
  const isEdit = !!rule;

  const form = useForm<PolicyFormData>({
    resolver: zodResolver(policySchema),
    defaultValues: {
      name: "",
      description: "",
      priority: 100,
      is_enabled: true,
      conditions: [],
      action: { provider: "openai", model: "gpt-4o-mini" },
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "conditions",
  });

  useEffect(() => {
    if (rule) {
      form.reset({
        name: rule.name,
        description: rule.description,
        priority: rule.priority,
        is_enabled: rule.is_enabled,
        conditions: rule.conditions,
        action: rule.action,
      });
    } else {
      form.reset({
        name: "",
        description: "",
        priority: 100,
        is_enabled: true,
        conditions: [],
        action: { provider: "openai", model: "gpt-4o-mini" },
      });
    }
  }, [rule, form]);

  const handleSubmit = form.handleSubmit((data) => {
    onSubmit(data);
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{isEdit ? "Modifier la politique" : "Créer une politique"}</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Name */}
          <div className="space-y-1">
            <Label htmlFor="name">Nom *</Label>
            <Input id="name" {...form.register("name")} placeholder="Ex: Finance — Données sensibles" />
            {form.formState.errors.name && (
              <p className="text-xs text-destructive">{form.formState.errors.name.message}</p>
            )}
          </div>

          {/* Description */}
          <div className="space-y-1">
            <Label htmlFor="description">Description</Label>
            <Textarea id="description" {...form.register("description")} rows={2} />
          </div>

          {/* Priority + Enabled */}
          <div className="flex gap-4">
            <div className="flex-1 space-y-1">
              <Label htmlFor="priority">Priorité</Label>
              <Input id="priority" type="number" {...form.register("priority")} min={1} max={1000} />
            </div>
            <div className="space-y-1">
              <Label>Activée</Label>
              <div className="h-10 flex items-center">
                <Switch
                  checked={form.watch("is_enabled")}
                  onCheckedChange={(v) => form.setValue("is_enabled", v)}
                />
              </div>
            </div>
          </div>

          {/* Conditions */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label>Conditions</Label>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => append({ field: "department", operator: "eq", value: "" })}
              >
                <Plus className="h-3 w-3 mr-1" /> Ajouter
              </Button>
            </div>
            {fields.map((field, idx) => (
              <div key={field.id} className="flex gap-2 items-start">
                <Select
                  value={form.watch(`conditions.${idx}.field`)}
                  onValueChange={(v) => form.setValue(`conditions.${idx}.field`, v)}
                >
                  <SelectTrigger className="flex-1">
                    <SelectValue placeholder="Champ" />
                  </SelectTrigger>
                  <SelectContent>
                    {CONDITION_FIELDS.map((f) => (
                      <SelectItem key={f} value={f}>{f}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Select
                  value={form.watch(`conditions.${idx}.operator`)}
                  onValueChange={(v) => form.setValue(`conditions.${idx}.operator`, v)}
                >
                  <SelectTrigger className="w-24">
                    <SelectValue placeholder="Op." />
                  </SelectTrigger>
                  <SelectContent>
                    {CONDITION_OPERATORS.map((op) => (
                      <SelectItem key={op} value={op}>{op}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Input
                  className="flex-1"
                  placeholder="Valeur"
                  {...form.register(`conditions.${idx}.value`)}
                />
                <Button type="button" variant="ghost" size="icon" onClick={() => remove(idx)}>
                  <Trash2 className="h-4 w-4 text-destructive" />
                </Button>
              </div>
            ))}
          </div>

          {/* Action */}
          <div className="rounded-md border p-4 space-y-3">
            <Label className="text-sm font-semibold">Action de routage</Label>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1">
                <Label htmlFor="provider">Fournisseur *</Label>
                <Select
                  value={form.watch("action.provider")}
                  onValueChange={(v) => form.setValue("action.provider", v)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {PROVIDERS.map((p) => (
                      <SelectItem key={p} value={p}>{p}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label htmlFor="model">Modèle *</Label>
                <Input
                  id="model"
                  {...form.register("action.model")}
                  placeholder="Ex: gpt-4o-mini"
                />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Annuler
            </Button>
            <Button type="submit" disabled={isPending}>
              {isPending ? "Enregistrement..." : isEdit ? "Mettre à jour" : "Créer"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
