import { useState } from "react";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import {
  Rss,
  Plus,
  Pencil,
  Trash2,
  CheckCircle2,
  XCircle,
  Clock,
  AlertCircle,
  Settings2,
  Zap,
  Globe,
  ChevronDown,
  ChevronUp,
  Save,
} from "lucide-react";
import { useLocalAuth } from "@/contexts/LocalAuthContext";
import { cn } from "@/lib/utils";

// ─── Types ────────────────────────────────────────────────────────────────────

type FeedType = "veille" | "aap";
type TypeVeille = "reglementaire" | "concurrentielle" | "technologique" | "informationnelle";
type CategorieAap = "Handicap" | "PA" | "Enfance" | "Précarité" | "Sanitaire" | "Autre";

interface AutoRule {
  keyword: string;
  value: string;
}

interface RssFeed {
  id: number;
  url: string;
  name: string;
  feedType: FeedType;
  defaultTypeVeille: TypeVeille | null;
  defaultCategorieAap: CategorieAap | null;
  autoRules: AutoRule[] | null;
  isActive: boolean;
  lastFetchedAt: Date | null;
  lastFetchStatus: "ok" | "error" | "pending" | null;
  lastFetchError: string | null;
}

// ─── Constantes ───────────────────────────────────────────────────────────────

const TYPE_VEILLE_LABELS: Record<TypeVeille, string> = {
  reglementaire: "Réglementaire",
  concurrentielle: "Concurrentielle",
  technologique: "Technologique",
  informationnelle: "Informationnelle",
};

const CATEGORIE_AAP_OPTIONS: CategorieAap[] = ["Handicap", "PA", "Enfance", "Précarité", "Sanitaire", "Autre"];
const TYPE_VEILLE_OPTIONS: TypeVeille[] = ["reglementaire", "concurrentielle", "technologique", "informationnelle"];

const INTERVAL_OPTIONS = [
  { value: 30, label: "30 minutes" },
  { value: 60, label: "1 heure" },
  { value: 120, label: "2 heures" },
  { value: 360, label: "6 heures" },
  { value: 720, label: "12 heures" },
  { value: 1440, label: "24 heures" },
];

// ─── Formulaire de flux ───────────────────────────────────────────────────────

interface FeedFormData {
  url: string;
  name: string;
  feedType: FeedType;
  defaultTypeVeille: TypeVeille | "";
  defaultCategorieAap: CategorieAap | "";
  autoRules: AutoRule[];
  isActive: boolean;
}

const EMPTY_FORM: FeedFormData = {
  url: "",
  name: "",
  feedType: "veille",
  defaultTypeVeille: "reglementaire",
  defaultCategorieAap: "",
  autoRules: [],
  isActive: true,
};

function FeedFormDialog({
  open,
  onClose,
  feed,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  feed: RssFeed | null;
  onSaved: () => void;
}) {
  const isEdit = !!feed;
  const [form, setForm] = useState<FeedFormData>(() =>
    feed
      ? {
          url: feed.url,
          name: feed.name,
          feedType: feed.feedType,
          defaultTypeVeille: feed.defaultTypeVeille ?? "",
          defaultCategorieAap: feed.defaultCategorieAap ?? "",
          autoRules: feed.autoRules ?? [],
          isActive: feed.isActive,
        }
      : { ...EMPTY_FORM }
  );
  const [newRuleKeyword, setNewRuleKeyword] = useState("");
  const [newRuleValue, setNewRuleValue] = useState("");

  const createMutation = trpc.rss.create.useMutation({
    onSuccess: () => {
      toast.success("Flux RSS ajouté");
      onSaved();
      onClose();
    },
    onError: (e) => toast.error("Erreur", { description: e.message }),
  });

  const updateMutation = trpc.rss.update.useMutation({
    onSuccess: () => {
      toast.success("Flux RSS mis à jour");
      onSaved();
      onClose();
    },
    onError: (e) => toast.error("Erreur", { description: e.message }),
  });

  const isPending = createMutation.isPending || updateMutation.isPending;

  const handleSubmit = () => {
    if (!form.url || !form.name) {
      toast.error("URL et nom sont requis");
      return;
    }
    const payload = {
      url: form.url,
      name: form.name,
      feedType: form.feedType,
      defaultTypeVeille: form.feedType === "veille" && form.defaultTypeVeille ? form.defaultTypeVeille : undefined,
      defaultCategorieAap: form.feedType === "aap" && form.defaultCategorieAap ? (form.defaultCategorieAap as CategorieAap) : undefined,
      autoRules: form.autoRules.length > 0 ? form.autoRules : undefined,
      isActive: form.isActive,
    };
    if (isEdit && feed) {
      updateMutation.mutate({ id: feed.id, ...payload });
    } else {
      createMutation.mutate(payload);
    }
  };

  const addRule = () => {
    if (!newRuleKeyword.trim() || !newRuleValue.trim()) return;
    setForm((f) => ({
      ...f,
      autoRules: [...f.autoRules, { keyword: newRuleKeyword.trim(), value: newRuleValue.trim() }],
    }));
    setNewRuleKeyword("");
    setNewRuleValue("");
  };

  const removeRule = (idx: number) => {
    setForm((f) => ({ ...f, autoRules: f.autoRules.filter((_, i) => i !== idx) }));
  };

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Rss className="h-5 w-5 text-primary" />
            {isEdit ? "Modifier le flux RSS" : "Ajouter un flux RSS"}
          </DialogTitle>
          <DialogDescription>
            Configurez l'URL, le type de contenu et les règles d'automatisme pour ce flux.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-5 py-2">
          {/* URL */}
          <div className="space-y-1.5">
            <Label htmlFor="feed-url" className="flex items-center gap-1.5">
              <Globe className="h-3.5 w-3.5" /> URL du flux RSS
            </Label>
            <Input
              id="feed-url"
              placeholder="https://www.legifrance.gouv.fr/rss/..."
              value={form.url}
              onChange={(e) => setForm((f) => ({ ...f, url: e.target.value }))}
            />
          </div>

          {/* Nom */}
          <div className="space-y-1.5">
            <Label htmlFor="feed-name">Nom descriptif</Label>
            <Input
              id="feed-name"
              placeholder="ex : Légifrance — Textes réglementaires"
              value={form.name}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            />
          </div>

          {/* Type de flux */}
          <div className="space-y-1.5">
            <Label>Type de contenu</Label>
            <div className="grid grid-cols-2 gap-3">
              {(["veille", "aap"] as FeedType[]).map((type) => (
                <button
                  key={type}
                  type="button"
                  onClick={() => setForm((f) => ({ ...f, feedType: type, defaultTypeVeille: type === "veille" ? "reglementaire" : "", defaultCategorieAap: type === "aap" ? "Handicap" : "" }))}
                  className={cn(
                    "flex items-center gap-3 p-3 rounded-lg border-2 text-left transition-all",
                    form.feedType === type
                      ? "border-primary bg-primary/5 text-primary"
                      : "border-border hover:border-primary/40"
                  )}
                >
                  <div className={cn("w-8 h-8 rounded-lg flex items-center justify-center", form.feedType === type ? "bg-primary text-primary-foreground" : "bg-muted")}>
                    {type === "veille" ? <Rss className="h-4 w-4" /> : <Zap className="h-4 w-4" />}
                  </div>
                  <div>
                    <p className="font-medium text-sm">{type === "veille" ? "Veille Stratégique" : "Appels à Projets"}</p>
                    <p className="text-xs text-muted-foreground">{type === "veille" ? "Réglementaire, concurrentielle…" : "Handicap, PA, Enfance…"}</p>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Valeur par défaut selon le type */}
          {form.feedType === "veille" && (
            <div className="space-y-1.5">
              <Label>Type de veille par défaut</Label>
              <Select
                value={form.defaultTypeVeille}
                onValueChange={(v) => setForm((f) => ({ ...f, defaultTypeVeille: v as TypeVeille }))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Choisir un type de veille" />
                </SelectTrigger>
                <SelectContent>
                  {TYPE_VEILLE_OPTIONS.map((t) => (
                    <SelectItem key={t} value={t}>{TYPE_VEILLE_LABELS[t]}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {form.feedType === "aap" && (
            <div className="space-y-1.5">
              <Label>Catégorie AAP par défaut</Label>
              <Select
                value={form.defaultCategorieAap}
                onValueChange={(v) => setForm((f) => ({ ...f, defaultCategorieAap: v as CategorieAap }))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Choisir une catégorie" />
                </SelectTrigger>
                <SelectContent>
                  {CATEGORIE_AAP_OPTIONS.map((c) => (
                    <SelectItem key={c} value={c}>{c}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          <Separator />

          {/* Règles d'automatisme */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Zap className="h-4 w-4 text-amber-500" />
              <Label className="text-sm font-semibold">Règles d'automatisme</Label>
            </div>
            <p className="text-xs text-muted-foreground">
              Si le titre ou le résumé d'un article contient le mot-clé, la {form.feedType === "veille" ? "catégorie de veille" : "catégorie AAP"} sera automatiquement assignée.
            </p>

            {/* Règles existantes */}
            {form.autoRules.length > 0 && (
              <div className="space-y-2">
                {form.autoRules.map((rule, idx) => (
                  <div key={idx} className="flex items-center gap-2 p-2 bg-muted/50 rounded-lg border">
                    <Badge variant="outline" className="font-mono text-xs shrink-0">{rule.keyword}</Badge>
                    <span className="text-xs text-muted-foreground">→</span>
                    <Badge className="text-xs shrink-0">{rule.value}</Badge>
                    <button
                      type="button"
                      onClick={() => removeRule(idx)}
                      className="ml-auto text-destructive hover:text-destructive/80 transition-colors"
                    >
                      <XCircle className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* Ajouter une règle */}
            <div className="flex gap-2 items-end">
              <div className="flex-1 space-y-1">
                <Label className="text-xs text-muted-foreground">Mot-clé</Label>
                <Input
                  placeholder="ex : SERAFIN"
                  value={newRuleKeyword}
                  onChange={(e) => setNewRuleKeyword(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && addRule()}
                  className="h-8 text-sm"
                />
              </div>
              <span className="text-muted-foreground mb-2">→</span>
              <div className="flex-1 space-y-1">
                <Label className="text-xs text-muted-foreground">
                  {form.feedType === "veille" ? "Type de veille" : "Catégorie AAP"}
                </Label>
                {form.feedType === "veille" ? (
                  <Select value={newRuleValue} onValueChange={setNewRuleValue}>
                    <SelectTrigger className="h-8 text-sm">
                      <SelectValue placeholder="Choisir…" />
                    </SelectTrigger>
                    <SelectContent>
                      {TYPE_VEILLE_OPTIONS.map((t) => (
                        <SelectItem key={t} value={t}>{TYPE_VEILLE_LABELS[t]}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <Select value={newRuleValue} onValueChange={setNewRuleValue}>
                    <SelectTrigger className="h-8 text-sm">
                      <SelectValue placeholder="Choisir…" />
                    </SelectTrigger>
                    <SelectContent>
                      {CATEGORIE_AAP_OPTIONS.map((c) => (
                        <SelectItem key={c} value={c}>{c}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              </div>
              <Button type="button" size="sm" variant="outline" onClick={addRule} className="h-8 mb-0">
                <Plus className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>

          <Separator />

          {/* Actif */}
          <div className="flex items-center justify-between">
            <div>
              <Label className="font-medium">Flux actif</Label>
              <p className="text-xs text-muted-foreground mt-0.5">Désactivez pour suspendre la lecture sans supprimer le flux</p>
            </div>
            <Switch
              checked={form.isActive}
              onCheckedChange={(v) => setForm((f) => ({ ...f, isActive: v }))}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={isPending}>Annuler</Button>
          <Button onClick={handleSubmit} disabled={isPending}>
            {isPending ? "Enregistrement…" : isEdit ? "Mettre à jour" : "Ajouter le flux"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Carte d'un flux ──────────────────────────────────────────────────────────

function FeedCard({
  feed,
  isAdmin,
  onEdit,
  onDelete,
  onToggle,
}: {
  feed: RssFeed;
  isAdmin: boolean;
  onEdit: () => void;
  onDelete: () => void;
  onToggle: (active: boolean) => void;
}) {
  const [rulesOpen, setRulesOpen] = useState(false);
  const rules = feed.autoRules ?? [];

  const statusIcon = () => {
    if (feed.lastFetchStatus === "ok") return <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />;
    if (feed.lastFetchStatus === "error") return <XCircle className="h-3.5 w-3.5 text-destructive" />;
    return <Clock className="h-3.5 w-3.5 text-muted-foreground" />;
  };

  const statusLabel = () => {
    if (feed.lastFetchStatus === "ok" && feed.lastFetchedAt) {
      return `Dernière lecture : ${new Date(feed.lastFetchedAt).toLocaleString("fr-FR")}`;
    }
    if (feed.lastFetchStatus === "error") return `Erreur : ${feed.lastFetchError ?? "inconnue"}`;
    return "Jamais lu";
  };

  return (
    <div className={cn(
      "border rounded-xl p-4 transition-all",
      feed.isActive ? "bg-card border-border" : "bg-muted/30 border-dashed border-muted-foreground/30 opacity-60"
    )}>
      <div className="flex items-start gap-3">
        {/* Icône type */}
        <div className={cn(
          "w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5",
          feed.feedType === "veille" ? "bg-blue-100 text-blue-600" : "bg-amber-100 text-amber-600"
        )}>
          {feed.feedType === "veille" ? <Rss className="h-5 w-5" /> : <Zap className="h-5 w-5" />}
        </div>

        {/* Infos */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-semibold text-sm truncate">{feed.name}</span>
            <Badge variant={feed.feedType === "veille" ? "secondary" : "outline"} className="text-xs shrink-0">
              {feed.feedType === "veille" ? "Veille" : "AAP"}
            </Badge>
            {feed.feedType === "veille" && feed.defaultTypeVeille && (
              <Badge variant="outline" className="text-xs shrink-0 border-blue-200 text-blue-700 bg-blue-50">
                {TYPE_VEILLE_LABELS[feed.defaultTypeVeille]}
              </Badge>
            )}
            {feed.feedType === "aap" && feed.defaultCategorieAap && (
              <Badge variant="outline" className="text-xs shrink-0 border-amber-200 text-amber-700 bg-amber-50">
                {feed.defaultCategorieAap}
              </Badge>
            )}
          </div>
          <p className="text-xs text-muted-foreground mt-1 truncate font-mono">{feed.url}</p>
          <div className="flex items-center gap-1.5 mt-1.5">
            {statusIcon()}
            <span className="text-xs text-muted-foreground">{statusLabel()}</span>
          </div>

          {/* Règles d'automatisme */}
          {rules.length > 0 && (
            <div className="mt-2">
              <button
                type="button"
                onClick={() => setRulesOpen(!rulesOpen)}
                className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
              >
                <Zap className="h-3 w-3 text-amber-500" />
                {rules.length} règle{rules.length > 1 ? "s" : ""} d'automatisme
                {rulesOpen ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
              </button>
              {rulesOpen && (
                <div className="mt-1.5 flex flex-wrap gap-1.5">
                  {rules.map((rule, i) => (
                    <span key={i} className="inline-flex items-center gap-1 text-xs bg-muted px-2 py-0.5 rounded-full border">
                      <span className="font-mono text-primary">{rule.keyword}</span>
                      <span className="text-muted-foreground">→</span>
                      <span>{rule.value}</span>
                    </span>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Actions */}
        {isAdmin && (
          <div className="flex items-center gap-2 flex-shrink-0">
            <Switch
              checked={feed.isActive}
              onCheckedChange={onToggle}
              className="scale-90"
            />
            <Button variant="ghost" size="icon" className="h-8 w-8" onClick={onEdit} title="Modifier">
              <Pencil className="h-3.5 w-3.5" />
            </Button>
            <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={onDelete} title="Supprimer">
              <Trash2 className="h-3.5 w-3.5" />
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Panneau de configuration ─────────────────────────────────────────────────

function SettingsPanel({ isAdmin }: { isAdmin: boolean }) {
  const { data: settings, refetch } = trpc.rss.getSettings.useQuery();
  const saveMutation = trpc.rss.saveSettings.useMutation({
    onSuccess: () => {
      toast.success("Paramètres RSS sauvegardés");
      refetch();
    },
    onError: (e) => toast.error("Erreur", { description: e.message }),
  });

  const [fetchMode, setFetchMode] = useState<"interval" | "scheduled">(settings?.fetchMode ?? "scheduled");
  const [fetchIntervalMinutes, setFetchIntervalMinutes] = useState(settings?.fetchIntervalMinutes ?? 360);
  const [scheduledTime, setScheduledTime] = useState(settings?.scheduledTime ?? "06:00");
  const [autoFetchEnabled, setAutoFetchEnabled] = useState(settings?.autoFetchEnabled ?? true);

  // Sync state when settings load
  if (settings && settings.fetchMode !== fetchMode && !saveMutation.isPending) {
    setFetchMode(settings.fetchMode);
    setFetchIntervalMinutes(settings.fetchIntervalMinutes);
    setScheduledTime(settings.scheduledTime ?? "06:00");
    setAutoFetchEnabled(settings.autoFetchEnabled);
  }

  const handleSave = () => {
    saveMutation.mutate({
      fetchMode,
      fetchIntervalMinutes,
      scheduledTime,
      autoFetchEnabled,
    });
  };

  return (
    <Card className="border-2 border-dashed border-primary/20">
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <Settings2 className="h-4 w-4 text-primary" />
          Paramètres de lecture automatique
        </CardTitle>
        <CardDescription>
          Configurez la fréquence et le mode de lecture des flux RSS.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        {/* Activation */}
        <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
          <div>
            <p className="font-medium text-sm">Lecture automatique</p>
            <p className="text-xs text-muted-foreground">Active la récupération périodique des flux</p>
          </div>
          <Switch
            checked={autoFetchEnabled}
            onCheckedChange={setAutoFetchEnabled}
            disabled={!isAdmin}
          />
        </div>

        {/* Mode */}
        <div className="space-y-2">
          <Label className="text-sm font-medium">Mode de planification</Label>
          <div className="grid grid-cols-2 gap-3">
            {(["scheduled", "interval"] as const).map((mode) => (
              <button
                key={mode}
                type="button"
                disabled={!isAdmin}
                onClick={() => setFetchMode(mode)}
                className={cn(
                  "flex items-center gap-2 p-3 rounded-lg border-2 text-left transition-all text-sm",
                  fetchMode === mode ? "border-primary bg-primary/5" : "border-border hover:border-primary/40",
                  !isAdmin && "opacity-50 cursor-not-allowed"
                )}
              >
                <Clock className={cn("h-4 w-4", fetchMode === mode ? "text-primary" : "text-muted-foreground")} />
                <div>
                  <p className="font-medium">{mode === "scheduled" ? "Heure fixe" : "Intervalle"}</p>
                  <p className="text-xs text-muted-foreground">{mode === "scheduled" ? "Chaque jour à une heure précise" : "Toutes les N minutes"}</p>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Paramètre selon le mode */}
        {fetchMode === "scheduled" ? (
          <div className="space-y-1.5">
            <Label className="text-sm">Heure de lecture quotidienne</Label>
            <Input
              type="time"
              value={scheduledTime}
              onChange={(e) => setScheduledTime(e.target.value)}
              disabled={!isAdmin}
              className="w-36"
            />
          </div>
        ) : (
          <div className="space-y-1.5">
            <Label className="text-sm">Intervalle de lecture</Label>
            <Select
              value={String(fetchIntervalMinutes)}
              onValueChange={(v) => setFetchIntervalMinutes(Number(v))}
              disabled={!isAdmin}
            >
              <SelectTrigger className="w-48">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {INTERVAL_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={String(opt.value)}>{opt.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        {isAdmin && (
          <Button onClick={handleSave} disabled={saveMutation.isPending} size="sm" className="gap-2">
            <Save className="h-3.5 w-3.5" />
            {saveMutation.isPending ? "Enregistrement…" : "Sauvegarder les paramètres"}
          </Button>
        )}
      </CardContent>
    </Card>
  );
}

// ─── Page principale ──────────────────────────────────────────────────────────

export default function RssFeeds() {
  const { user } = useLocalAuth();
  const isAdmin = user?.role === "admin";

  const { data: feeds = [], refetch, isLoading } = trpc.rss.list.useQuery();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [editFeed, setEditFeed] = useState<RssFeed | null>(null);
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [filterType, setFilterType] = useState<"all" | "veille" | "aap">("all");

  const toggleMutation = trpc.rss.toggleActive.useMutation({
    onSuccess: () => refetch(),
    onError: (e) => toast.error("Erreur", { description: e.message }),
  });

  const deleteMutation = trpc.rss.delete.useMutation({
    onSuccess: () => {
      toast.success("Flux supprimé");
      setDeleteId(null);
      refetch();
    },
    onError: (e) => toast.error("Erreur", { description: e.message }),
  });

  const filteredFeeds = feeds.filter((f) => filterType === "all" || f.feedType === filterType);
  const veilleCount = feeds.filter((f) => f.feedType === "veille").length;
  const aapCount = feeds.filter((f) => f.feedType === "aap").length;
  const activeCount = feeds.filter((f) => f.isActive).length;

  return (
    <div className="p-6 max-w-5xl mx-auto space-y-6">
      {/* En-tête */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Rss className="h-6 w-6 text-primary" />
            Flux RSS
          </h1>
          <p className="text-muted-foreground text-sm mt-1">
            Gérez les sources RSS qui alimentent automatiquement la veille réglementaire et les appels à projets.
          </p>
        </div>
        {isAdmin && (
          <Button onClick={() => { setEditFeed(null); setDialogOpen(true); }} className="gap-2 shrink-0">
            <Plus className="h-4 w-4" />
            Ajouter un flux
          </Button>
        )}
      </div>

      {/* Statistiques */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "Total", value: feeds.length, color: "text-foreground" },
          { label: "Actifs", value: activeCount, color: "text-green-600" },
          { label: "Veille", value: veilleCount, color: "text-blue-600" },
          { label: "AAP", value: aapCount, color: "text-amber-600" },
        ].map((stat) => (
          <div key={stat.label} className="bg-card border rounded-xl p-3 text-center">
            <p className={cn("text-2xl font-bold", stat.color)}>{stat.value}</p>
            <p className="text-xs text-muted-foreground mt-0.5">{stat.label}</p>
          </div>
        ))}
      </div>

      {/* Filtres */}
      <div className="flex gap-2 flex-wrap">
        {(["all", "veille", "aap"] as const).map((type) => (
          <Button
            key={type}
            variant={filterType === type ? "default" : "outline"}
            size="sm"
            onClick={() => setFilterType(type)}
            className="gap-1.5"
          >
            {type === "all" ? "Tous" : type === "veille" ? <><Rss className="h-3.5 w-3.5" /> Veille</> : <><Zap className="h-3.5 w-3.5" /> AAP</>}
            <Badge variant="secondary" className="ml-1 text-xs px-1.5">
              {type === "all" ? feeds.length : type === "veille" ? veilleCount : aapCount}
            </Badge>
          </Button>
        ))}
      </div>

      {/* Liste des flux */}
      <div className="space-y-3">
        {isLoading ? (
          <div className="text-center py-12 text-muted-foreground">
            <Rss className="h-8 w-8 mx-auto mb-2 animate-pulse" />
            <p className="text-sm">Chargement des flux…</p>
          </div>
        ) : filteredFeeds.length === 0 ? (
          <div className="text-center py-12 border-2 border-dashed rounded-xl">
            <Rss className="h-10 w-10 mx-auto mb-3 text-muted-foreground/40" />
            <p className="font-medium text-muted-foreground">Aucun flux RSS configuré</p>
            {isAdmin && (
              <Button variant="outline" size="sm" className="mt-3 gap-2" onClick={() => { setEditFeed(null); setDialogOpen(true); }}>
                <Plus className="h-3.5 w-3.5" />
                Ajouter votre premier flux
              </Button>
            )}
          </div>
        ) : (
          filteredFeeds.map((feed) => (
            <FeedCard
              key={feed.id}
              feed={feed as RssFeed}
              isAdmin={isAdmin}
              onEdit={() => { setEditFeed(feed as RssFeed); setDialogOpen(true); }}
              onDelete={() => setDeleteId(feed.id)}
              onToggle={(active) => toggleMutation.mutate({ id: feed.id, isActive: active })}
            />
          ))
        )}
      </div>

      {/* Paramètres de lecture */}
      <SettingsPanel isAdmin={isAdmin} />

      {/* Informations sur les automatismes */}
      <Card className="bg-blue-50/50 border-blue-200">
        <CardContent className="pt-4 pb-4">
          <div className="flex gap-3">
            <AlertCircle className="h-5 w-5 text-blue-500 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <p className="text-sm font-medium text-blue-800">Comment fonctionnent les règles d'automatisme ?</p>
              <p className="text-xs text-blue-700">
                Lors de la lecture d'un flux, chaque article est analysé. Si son titre ou son résumé contient un mot-clé défini dans les règles, la catégorie ou le type de veille correspondant lui est automatiquement assigné. Si aucune règle ne correspond, la valeur par défaut du flux est utilisée.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Dialog ajout/édition */}
      <FeedFormDialog
        open={dialogOpen}
        onClose={() => { setDialogOpen(false); setEditFeed(null); }}
        feed={editFeed}
        onSaved={() => refetch()}
      />

      {/* Confirmation suppression */}
      <AlertDialog open={deleteId !== null} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer ce flux RSS ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. Le flux sera définitivement supprimé mais les entrées déjà importées seront conservées.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Annuler</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Supprimer
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
