// Components/Policy/TransferModal.jsx
import { useEffect, useMemo, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faXmark,
  faMagnifyingGlass,
  faRightLeft,
  faCircleCheck,
} from "@fortawesome/free-solid-svg-icons";

export default function TransferModal({
  open,
  onClose,
  companies = [],
  onSelect, // (company) => void
}) {
  const [q, setQ] = useState("");
  const [selectedId, setSelectedId] = useState(null);

  useEffect(() => {
    if (!open) return;
    setQ("");
    setSelectedId(null);
  }, [open]);

  const filtered = useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return companies;
    return companies.filter((c) => String(c.name).toLowerCase().includes(s));
  }, [q, companies]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose?.();
    };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const confirm = () => {
    const company = companies.find((c) => c.id === selectedId);
    if (!company) return;
    onSelect?.(company);
    onClose?.();
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[80] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />

      <div className="relative w-full max-w-xl rounded-3xl border border-black/10 bg-white shadow-2xl overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-black/10 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-black/55">
              <FontAwesomeIcon icon={faRightLeft} />
            </span>
            <div className="text-lg font-extrabold text-black/85">
              Transfer Şirketi Seç
            </div>
          </div>

          <button
            onClick={onClose}
            className="h-10 w-10 cursor-pointer rounded-2xl border border-black/10 bg-white hover:bg-black/[0.03] transition"
            aria-label="Kapat"
          >
            <FontAwesomeIcon icon={faXmark} />
          </button>
        </div>

        {/* Search */}
        <div className="px-6 pt-5">
          <div className="relative">
            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-black/35">
              <FontAwesomeIcon icon={faMagnifyingGlass} />
            </span>
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Şirket ara..."
              className="w-full rounded-2xl border border-black/10 bg-white pl-11 pr-4 py-3 text-sm outline-none focus:ring-4 focus:ring-red-500/10 focus:border-red-500/30 transition"
            />
          </div>
        </div>

        {/* List */}
        <div className="px-6 py-4 max-h-[380px] overflow-auto">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {filtered.map((c) => {
              const active = selectedId === c.id;
              return (
                <button
                  key={c.id}
                  type="button"
                  onClick={() => setSelectedId(c.id)}
                  className={[
                    "group text-left cursor-pointer rounded-3xl border bg-white p-4 transition",
                    "hover:-translate-y-[1px] hover:shadow-md",
                    active
                      ? "border-red-200 bg-red-50"
                      : "border-black/10 hover:bg-black/[0.02]",
                  ].join(" ")}
                >
                  <div className="flex items-center gap-3">
                    <LogoCircleImage
                      src={`/companies/${c.logo}`} // ✅ put images in /public/logos/
                      alt={c.name}
                    />
                    <div className="flex-1">
                      <div className="text-sm font-extrabold text-black/80">
                        {c.name}
                      </div>
                      {c.subtitle ? (
                        <div className="mt-0.5 text-xs text-black/50">
                          {c.subtitle}
                        </div>
                      ) : (
                        <div className="mt-0.5 text-xs text-black/45">
                          Transfer için seç
                        </div>
                      )}
                    </div>

                    <div
                      className={[
                        "h-9 w-9 rounded-2xl border grid place-items-center transition",
                        active
                          ? "border-red-200 bg-white text-red-600"
                          : "border-black/10 bg-white text-black/35 group-hover:text-black/55",
                      ].join(" ")}
                    >
                      <FontAwesomeIcon icon={faCircleCheck} />
                    </div>
                  </div>
                </button>
              );
            })}

            {filtered.length === 0 && (
              <div className="col-span-full rounded-3xl border border-black/10 bg-white p-6 text-center text-sm text-black/55">
                Şirket bulunamadı.
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-5 border-t border-black/10 flex items-center justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded-2xl cursor-pointer border border-black/10 bg-white px-4 py-2.5 text-sm font-semibold text-black/70 hover:bg-black/[0.03] transition"
          >
            İptal
          </button>
          <button
            type="button"
            disabled={!selectedId}
            onClick={confirm}
            className="rounded-2xl cursor-pointer px-4 py-2.5 text-sm font-semibold text-white bg-gradient-to-r from-red-600 to-red-500 shadow-lg shadow-red-600/15 hover:brightness-[1.02]  transition disabled:opacity-60 disabled:cursor-not-allowed"
          >
            Seç ve Devam Et
          </button>
        </div>
      </div>
    </div>
  );
}

function LogoCircleImage({ src, alt }) {
  return (
    <div className="h-12 w-12 rounded-3xl border border-black/10 bg-white shadow-sm overflow-hidden grid place-items-center">
      <img
        src={src}
        alt={alt || "logo"}
        className="h-full w-full object-contain p-2"
        loading="lazy"
      />
    </div>
  );
}
