"use client";

import { useState } from "react";
import { ExternalLink, Save, Lock } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { McpEnvVar } from "@/lib/api/settings";
import { useUpdateMcpEnv } from "@/lib/api/settings";
import { toast } from "sonner";
import { DriftBadge } from "./drift-badge";
import { EnvVarEditor } from "./env-var-editor";

type Props = {
  spec: McpEnvVar;
  coolifyAppUuid: string;
  coolifyAvailable: boolean;
  onPendingRedeploy: () => void;
};

export function EnvVarRow({
  spec,
  coolifyAppUuid,
  coolifyAvailable,
  onPendingRedeploy,
}: Props) {
  const [draft, setDraft] = useState<string>(spec.coolify_value ?? "");
  const update = useUpdateMcpEnv();
  const dirty = draft !== (spec.coolify_value ?? "");

  function handleSave() {
    update.mutate(
      { key: spec.key, value: draft },
      {
        onSuccess: (res) => {
          toast.success(res.message);
          onPendingRedeploy();
        },
        onError: (err) => toast.error(`שגיאה: ${err.message}`),
      },
    );
  }

  const coolifyEnvUrl =
    `https://coolify.nautilus.marcusgroup.org/project/applications/${coolifyAppUuid}/environment-variables`;

  return (
    <div className="px-5 py-4 border-b border-rule-soft last:border-b-0">
      {/* envtop — key + type chip + secret chip + drift/synced chip */}
      <div className="flex items-center gap-2 flex-wrap">
        <code className="font-mono text-[0.84rem] font-semibold text-navy" dir="ltr">
          {spec.key}
        </code>
        <span className="inline-flex items-center rounded-full bg-info-bg text-info text-[0.72rem] font-semibold px-2.5 py-0.5">
          {spec.type}
        </span>
        {spec.is_secret && (
          <span className="inline-flex items-center gap-1 rounded-full bg-navy text-white text-[0.72rem] font-semibold px-2.5 py-0.5">
            <Lock className="w-3 h-3" />
            secret
          </span>
        )}
        <DriftBadge drift={spec.drift} coolifyAvailable={coolifyAvailable} />
        {spec.has_duplicates && (
          <span className="inline-flex items-center rounded-full bg-warn-bg text-warn text-[0.72rem] font-semibold px-2.5 py-0.5">
            duplicates
          </span>
        )}
      </div>
      {spec.description && (
        <p className="text-[0.82rem] text-ink-muted mt-1">{spec.description}</p>
      )}

      {/* vals — Coolify value | Container value (+pending) | save (mockup .vals 3-col) */}
      <div className="grid grid-cols-1 md:grid-cols-[1fr_1fr_auto] gap-3.5 items-end mt-3.5">
        <div>
          <span className="block text-[0.72rem] text-ink-muted font-semibold mb-1">
            Coolify:
          </span>
          {spec.is_editable ? (
            <EnvVarEditor
              spec={spec}
              value={draft}
              onChange={setDraft}
              disabled={update.isPending}
            />
          ) : (
            <a
              href={coolifyEnvUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="font-mono text-[0.81rem] text-gold-deep hover:underline flex items-center gap-1"
              dir="ltr"
            >
              {spec.coolify_value ?? "— לא מוגדר —"}
              <ExternalLink className="w-3 h-3 shrink-0" />
            </a>
          )}
        </div>
        <div>
          <span className="block text-[0.72rem] text-ink-muted font-semibold mb-1">
            Container:
          </span>
          <div className="font-mono text-[0.81rem] text-ink-soft bg-rule-soft rounded-md px-3 py-2 flex items-center gap-2 flex-wrap" dir="ltr">
            <span>{spec.container_value ?? "— לא מוגדר —"}</span>
            {/* ADM-5 (INV-IA5/INV-IA6): Coolify ≠ Container ⇒ container is stale
                until a redeploy — say so in plain Hebrew right here. */}
            {coolifyAvailable && spec.drift && (
              <span
                className="inline-flex items-center rounded-full bg-warn-bg text-warn border border-warn text-[0.7rem] font-semibold px-2 py-0.5"
                dir="rtl"
                title="הערך נשמר ב-Coolify אך הקונטיינר עדיין מריץ את הקודם — נדרש redeploy"
              >
                ממתין ל-redeploy
              </span>
            )}
          </div>
        </div>
        <div className="flex md:block items-end">
          {spec.is_editable ? (
            <Button
              size="sm"
              onClick={handleSave}
              disabled={!dirty || update.isPending}
              variant={dirty ? "default" : "outline"}
              className={dirty ? "bg-gold text-white hover:bg-gold-deep border-transparent" : ""}
            >
              <Save className="w-3.5 h-3.5" data-icon="inline-start" />
              {update.isPending ? "שומר..." : "שמור"}
            </Button>
          ) : (
            <a
              href={coolifyEnvUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1 rounded-md border border-rule text-navy px-4 py-1.5 text-[0.81rem] font-semibold hover:bg-gold-wash"
            >
              ערוך ב-Coolify
              <ExternalLink className="w-3 h-3" />
            </a>
          )}
        </div>
      </div>
    </div>
  );
}
