"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2, Search } from "lucide-react";
import { registryApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";
import { PublicPageHeader } from "@/components/shared/public-page";
import { Pagination } from "@/components/ui/pagination";
import type { RegistryEntry, RegistryType } from "@/types";

/**
 * Public registry listing — approved entries only. Contact details (email,
 * phone, mobile, address) are masked per the owner's decision (2026-08-26):
 * they are visible only to admins in the dashboard. Anyone needing to reach
 * a registrant goes through the contact form.
 */
export function RegistryPage({
  type,
  titleHi,
  titleEn,
}: {
  type: RegistryType;
  titleHi: string;
  titleEn: string;
}) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";

  const [query, setQuery] = useState("");
  const [submitted, setSubmitted] = useState("");
  const [page, setPage] = useState(0);

  const { data, isLoading } = useQuery({
    queryKey: ["registry", type, submitted, page],
    queryFn: async () => (await registryApi.list(type, submitted, page)).data,
  });

  const entries: RegistryEntry[] = data?.content ?? [];
  const isSupervisor = type === "SUPERVISOR";

  const onSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(0);
    setSubmitted(query.trim());
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <PublicPageHeader
        titleHi={titleHi}
        titleEn={titleEn}
        breadcrumbs={[
          { label: hi ? "होम" : "Home", href: "/" },
          { label: hi ? "पर्यवेक्षक डेस्क" : "Supervisor's Desk", href: "/registry/supervisors" },
          { label: hi ? titleHi : titleEn },
        ]}
      />

      <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
        <form onSubmit={onSearch} className="mb-8 flex max-w-2xl gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={
                hi
                  ? "नाम, विषय, विश्वविद्यालय खोजें…"
                  : "Search name, subject, university…"
              }
              className="w-full rounded-md border border-gray-300 bg-white py-2.5 pl-9 pr-3 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
          </div>
          <button
            type="submit"
            className="rounded-md bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700"
          >
            {hi ? "खोजें" : "Search"}
          </button>
        </form>

        {isLoading ? (
          <div className="flex justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
          </div>
        ) : entries.length === 0 ? (
          <p className="py-10 text-center text-sm text-gray-500">
            {hi ? "कोई प्रविष्टि नहीं मिली।" : "No entries found."}
          </p>
        ) : (
          <>
            <p className="mb-3 text-xs text-gray-500">
              {data.totalElements} {hi ? "प्रविष्टियाँ" : "entries"}
              <span className="ml-2 text-gray-400">
                {hi
                  ? "· संपर्क विवरण हेतु संपर्क पृष्ठ से अनुरोध करें"
                  : "· for contact details, request via the contact page"}
              </span>
            </p>
            <div className="overflow-x-auto rounded-lg border border-gray-200 bg-white shadow-sm">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b-2 border-indigo-800 bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-600">
                    <th className="px-4 py-3">{hi ? "नाम" : "Name"}</th>
                    {isSupervisor ? (
                      <>
                        <th className="px-4 py-3">{hi ? "पदनाम" : "Designation"}</th>
                        <th className="px-4 py-3">{hi ? "विश्वविद्यालय / संस्थान" : "University / Institution"}</th>
                        <th className="px-4 py-3">{hi ? "विषय" : "Subject"}</th>
                        <th className="px-4 py-3">{hi ? "रुचि" : "Interest"}</th>
                      </>
                    ) : (
                      <>
                        <th className="px-4 py-3">{hi ? "विषय (टॉपिक)" : "Topic"}</th>
                        <th className="px-4 py-3">{hi ? "पर्यवेक्षक" : "Supervisor"}</th>
                        <th className="px-4 py-3">{hi ? "विश्वविद्यालय" : "University"}</th>
                        <th className="px-4 py-3">{hi ? "वर्ष" : "Year"}</th>
                      </>
                    )}
                  </tr>
                </thead>
                <tbody>
                  {entries.map((e) => (
                    <tr key={e.id} className="border-b border-gray-100 align-top last:border-b-0 hover:bg-indigo-50/40">
                      <td className="px-4 py-3 font-medium text-gray-900">{e.name}</td>
                      {isSupervisor ? (
                        <>
                          <td className="px-4 py-3 text-gray-700">{e.designation}</td>
                          <td className="px-4 py-3 text-gray-600">{e.university}</td>
                          <td className="px-4 py-3 text-gray-700">{e.subject}</td>
                          <td className="px-4 py-3 text-gray-600">{e.interest}</td>
                        </>
                      ) : (
                        <>
                          <td className="px-4 py-3 text-gray-700">{e.topic}</td>
                          <td className="px-4 py-3 text-gray-700">{e.supervisor}</td>
                          <td className="px-4 py-3 text-gray-600">{e.university}</td>
                          <td className="px-4 py-3 text-gray-700">{e.researchYear}</td>
                        </>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="mt-6">
              <Pagination
                page={page}
                totalPages={data.totalPages ?? 1}
                onPageChange={setPage}
              />
            </div>
          </>
        )}
      </div>
    </div>
  );
}
