"use client";

import { useState, useMemo } from "react";
import { RefreshCw, AlertCircle } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import {
  useMcpEnv,
  useMcpRedeploy,
  type McpEnvVar,
  type EnvCategory,
} from "@/lib/api/settings";
import { toast } from "sonner";
import { EnvVarRow } from "./env-var-row";

const CATEGORY_LABELS: Record<EnvCategory, string> = {
  multimodal: "Multimodal",
  rerank: "Rerank",
  halacha: "Halacha",
  general: "כללי",
  credentials: "אישורים",
  connection: "חיבורים",
};

const CATEGORY_ORDER: EnvCategory[] = [
  "multimodal", "rerank", "halacha", "general", "credentials", "connection",
];

export function EnvironmentTab() {
  const { data, isPending, error } = useMcpEnv();
  const redeploy = useMcpRedeploy();
  const [pendingRedeploy, setPendingRedeploy] = useState(false);

  const grouped = useMemo(() => {
    if (!data?.vars) return new Map<EnvCategory, McpEnvVar[]>();
    const m = new Map<EnvCategory, McpEnvVar[]>();
    for (const v of data.vars) {
      const arr = m.get(v.category) ?? [];
      arr.push(v);
      m.set(v.category, arr);
    }
    return m;
  }, [data]);

  function handleRedeploy() {
    redeploy.mutate(undefined, {
      onSuccess: (res) => {
        toast.success(res.message);
        setPendingRedeploy(false);
      },
      onError: (err) => toast.error(`Redeploy נכשל: ${err.message}`),
    });
  }

  if (isPending) return <Skeleton className="h-96 w-full" />;
  if (error) {
    return (
      <Card className="bg-surface border-danger/40">
        <CardContent className="p-6 flex items-center gap-3 text-danger">
          <AlertCircle className="w-5 h-5" />
          <span>שגיאה בטעינת env vars: {error.message}</span>
        </CardContent>
      </Card>
    );
  }
  if (!data) return null;

  const coolifyAvailable = data.errors.length === 0;
  const driftCount = data.vars.filter((v) => v.drift).length;
  const duplicatesCount = data.vars.filter((v) => v.has_duplicates).length;

  return (
    <div className="space-y-5">
      {/* summary band — Coolify app id + drift/dup counts + redeploy CTA */}
      <Card className="bg-surface border-rule shadow-sm">
        <CardContent className="px-6 py-4 flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-3 flex-wrap text-sm">
            <Badge variant="outline">
              Coolify app: <code dir="ltr" className="ms-1">{data.coolify_app_uuid.slice(0, 8)}…</code>
            </Badge>
            {driftCount > 0 && (
              <span className="inline-flex items-center rounded-full bg-warn-bg text-warn text-[0.72rem] font-semibold px-2.5 py-0.5">
                {driftCount} ב-Drift
              </span>
            )}
            {duplicatesCount > 0 && (
              <span className="inline-flex items-center rounded-full bg-warn-bg text-warn text-[0.72rem] font-semibold px-2.5 py-0.5">
                {duplicatesCount} duplicates
              </span>
            )}
            {data.errors.length > 0 && (
              <span className="inline-flex items-center rounded-full bg-danger-bg text-danger text-[0.72rem] font-semibold px-2.5 py-0.5">
                {data.errors.join(", ")}
              </span>
            )}
          </div>
          <Button
            onClick={handleRedeploy}
            disabled={redeploy.isPending}
            size="sm"
            className={pendingRedeploy ? "bg-gold text-white hover:bg-gold-deep border-transparent" : ""}
            variant={pendingRedeploy ? "default" : "outline"}
          >
            <RefreshCw className={redeploy.isPending ? "w-3.5 h-3.5 animate-spin" : "w-3.5 h-3.5"} data-icon="inline-start" />
            {redeploy.isPending ? "פורס מחדש..." : "פרוס מחדש"}
          </Button>
        </CardContent>
      </Card>

      {CATEGORY_ORDER.map((cat) => {
        const vars = grouped.get(cat);
        if (!vars || vars.length === 0) return null;
        const catDrift = vars.filter((v) => v.drift).length;
        return (
          <div
            key={cat}
            className="rounded-lg border border-rule bg-surface shadow-sm overflow-hidden"
          >
            {/* panel header (.ph) — parchment band: title + count + drift chip */}
            <div className="flex items-center justify-between gap-3 px-5 py-4 border-b border-rule bg-parchment">
              <div>
                <h2 className="text-navy text-base font-semibold mb-0 flex items-center gap-2">
                  {CATEGORY_LABELS[cat]}
                  <span className="text-[0.72rem] text-ink-muted font-medium tabular-nums">
                    ({vars.length})
                  </span>
                </h2>
                <p className="text-[0.78rem] text-ink-muted mt-0.5">
                  מקור-האמת הוא Coolify. שינוי נכנס לתוקף רק לאחר redeploy של הקונטיינר.
                </p>
              </div>
              {coolifyAvailable && catDrift > 0 && (
                <span className="inline-flex items-center rounded-full bg-warn-bg text-warn text-[0.72rem] font-semibold px-2.5 py-0.5 shrink-0">
                  {catDrift} ב-Drift
                </span>
              )}
            </div>
            {vars.map((v) => (
              <EnvVarRow
                key={v.key}
                spec={v}
                coolifyAppUuid={data.coolify_app_uuid}
                coolifyAvailable={coolifyAvailable}
                onPendingRedeploy={() => setPendingRedeploy(true)}
              />
            ))}
          </div>
        );
      })}
    </div>
  );
}
