"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Plus, Search, Edit, User, Target, Activity, X } from "lucide-react";

type ProfileRow = {
  id: string;
  name: string;
  email: string | null;
  role: string;
  avatar?: string | null;
  providerUserId: number | null;
  createdAt: string;
  _count?: { sessions: number };
};

type OfficeProviderRow = { id: number; name: string; email: string | null };

export default function PractitionersPage() {
  const [practitioners, setPractitioners] = useState<ProfileRow[]>([]);
  const [providers, setProviders] = useState<OfficeProviderRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [providersLoading, setProvidersLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [selectedProviderId, setSelectedProviderId] = useState<string>("");

  const fetchPractitioners = () => {
    setLoading(true);
    fetch("/api/profiles")
      .then((res) => res.json())
      .then((json) => {
        if (json.success) setPractitioners(json.data);
        setLoading(false);
      });
  };

  const fetchProviders = () => {
    setProvidersLoading(true);
    fetch("/api/providers")
      .then((res) => res.json())
      .then((json) => {
        if (json.success) setProviders(json.data);
        setProvidersLoading(false);
      })
      .catch(() => setProvidersLoading(false));
  };

  useEffect(() => {
    fetchPractitioners();
  }, []);

  useEffect(() => {
    if (isModalOpen) {
      fetchProviders();
    }
  }, [isModalOpen]);

  const enlistedIds = new Set(
    practitioners.map((p) => p.providerUserId).filter((id): id is number => id != null)
  );

  const availableProviders = providers.filter((p) => !enlistedIds.has(p.id));

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    const id = Number(selectedProviderId);
    if (!Number.isFinite(id) || id <= 0) {
      alert("Select a provider from the list.");
      return;
    }
    setIsCreating(true);
    try {
      const res = await fetch("/api/profiles", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ providerUserId: id }),
      });
      const json = await res.json();
      if (json.success) {
        setIsModalOpen(false);
        setSelectedProviderId("");
        fetchPractitioners();
      } else {
        alert("Error creating practitioner: " + (json.error || res.status));
      }
    } catch {
      alert("Failed to connect to API");
    } finally {
      setIsCreating(false);
    }
  };

  const filtered = practitioners.filter(
    (p) =>
      p.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      p.role.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (p.email && p.email.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  if (loading)
    return (
      <div className="h-full flex items-center justify-center font-mono text-[#044f54] uppercase tracking-widest text-xs">
        Scanning Operative Files...
      </div>
    );

  return (
    <div className="space-y-6 max-w-6xl mx-auto animate-in fade-in duration-500">
      <div className="flex justify-between items-end border-b border-[#044f54]/20 pb-4 text-[#044f54]">
        <div>
          <h2 className="text-2xl font-serif italic">Operative Directory</h2>
          <p className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-[0.2em] mt-1">
            Authorized RMS Training Candidates
          </p>
        </div>
        <div className="flex gap-4 items-center">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#044f54]/40" size={16} />
            <input
              type="text"
              placeholder="SEARCH CANDIDATES..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 bg-white border border-[#044f54]/20 rounded font-mono text-[10px] uppercase tracking-wider focus:border-[#044f54] outline-none w-64"
            />
          </div>
          <button
            type="button"
            onClick={() => setIsModalOpen(true)}
            className="bg-[#044f54] text-white px-6 py-2 rounded font-bold uppercase tracking-widest text-[10px] shadow-lg shadow-[#044f54]/20 hover:bg-[#044f54]/90 transition-all flex items-center gap-2"
          >
            <Plus size={14} />
            Enlist Operative
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filtered.map((p) => (
          <div
            key={p.id}
            className="bg-white border border-[#044f54]/10 rounded-lg overflow-hidden flex flex-col group hover:border-[#044f54]/40 transition-all"
          >
            <div className="p-5 flex items-start justify-between border-b border-[#044f54]/5">
              <div className="flex items-center gap-4">
                <div className="w-14 h-14 rounded-full bg-[#044f54]/5 border border-[#044f54]/10 flex items-center justify-center text-[#044f54] overflow-hidden">
                  {p.avatar ? (
                    <img src={p.avatar} alt={p.name} className="w-full h-full object-cover" />
                  ) : (
                    <User size={28} />
                  )}
                </div>
                <div>
                  <h3 className="font-bold text-[#044f54] uppercase tracking-wider text-sm">{p.name}</h3>
                  <div className="text-[10px] font-mono text-[#044f54]/50 uppercase">{p.role}</div>
                  {p.email ? (
                    <div className="text-[10px] font-mono text-[#044f54]/40 mt-1 truncate max-w-[180px]">
                      {p.email}
                    </div>
                  ) : null}
                </div>
              </div>
              <Link
                href={`/admin/practitioners/${p.id}`}
                className="text-[#044f54]/30 hover:text-[#044f54] p-1 transition-colors"
              >
                <Edit size={16} />
              </Link>
            </div>

            <div className="p-5 bg-slate-50/50 grid grid-cols-2 gap-4 flex-1">
              <div className="flex flex-col gap-1">
                <div className="flex items-center gap-1 text-[9px] font-mono text-[#044f54]/40 uppercase tracking-wider">
                  <Activity size={10} /> Sessions
                </div>
                <div className="text-xl font-bold text-[#044f54]">{p._count?.sessions || 0}</div>
              </div>
              <div className="flex flex-col gap-1 border-l border-[#044f54]/5 pl-4">
                <div className="flex items-center gap-1 text-[9px] font-mono text-[#044f54]/40 uppercase tracking-wider">
                  <Target size={10} /> Progress
                </div>
                <div className="text-xl font-bold text-[#044f54]">0%</div>
              </div>
            </div>

            <div className="px-5 py-3 border-t border-[#044f54]/5 flex justify-between items-center text-[10px] font-mono text-[#044f54]/40">
              <span>ID: {p.id.substring(0, 8)}</span>
              <span className="uppercase tracking-widest">
                Enrolled {new Date(p.createdAt).toLocaleDateString()}
              </span>
            </div>
          </div>
        ))}
      </div>

      {isModalOpen && (
        <div className="fixed inset-0 bg-[#044f54]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
          <div className="bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.2)] w-full max-w-md rounded overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="absolute inset-0 pointer-events-none bg-[repeating-linear-gradient(0deg,transparent,transparent_2px,rgba(4,79,84,0.05)_2px,rgba(4,79,84,0.05)_4px)]" />

            <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center relative z-10">
              <div className="flex items-center gap-3">
                <div className="w-6 h-6 bg-[#044f54] flex items-center justify-center text-white font-black uppercase text-[10px] tracking-widest rounded-sm">
                  ADM
                </div>
                <span className="text-[#044f54] font-bold text-xs tracking-widest uppercase">
                  Enlist New Operative
                </span>
              </div>
              <button type="button" onClick={() => setIsModalOpen(false)} className="text-[#044f54]/60 hover:text-[#044f54]">
                <X size={18} />
              </button>
            </div>

            <form onSubmit={handleCreate} className="p-6 space-y-4 relative z-10 text-[#044f54]">
              <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                <label className="text-[9px] font-mono text-[#044f54]/50 uppercase tracking-wider">
                  System provider
                </label>
                <select
                  required
                  value={selectedProviderId}
                  onChange={(e) => setSelectedProviderId(e.target.value)}
                  disabled={providersLoading}
                  className="bg-transparent outline-none text-sm font-medium text-[#044f54] w-full"
                >
                  <option value="">
                    {providersLoading ? "LOADING PROVIDERS…" : "— SELECT PROVIDER —"}
                  </option>
                  {availableProviders.map((pr) => (
                    <option key={pr.id} value={String(pr.id)}>
                      {pr.name}
                      {pr.email ? ` (${pr.email})` : ""}
                    </option>
                  ))}
                </select>
                {!providersLoading && availableProviders.length === 0 ? (
                  <p className="text-[10px] text-[#044f54]/60 mt-1">
                    All active providers are already enlisted, or the Office list is empty.
                  </p>
                ) : null}
              </div>

              <div className="flex justify-end gap-3 pt-4">
                <button
                  type="submit"
                  disabled={isCreating || providersLoading || availableProviders.length === 0}
                  className="bg-[#044f54] text-white px-8 py-3 rounded font-bold uppercase tracking-widest text-[10px] w-full shadow-lg shadow-[#044f54]/20 hover:bg-[#044f54]/90 disabled:opacity-50"
                >
                  {isCreating ? "ENLISTING..." : "COMMIT ENLISTMENT"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
