"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { AuthSessionBridge } from "../components/AuthSessionBridge";
import { SessionControls } from "../components/SessionControls";
import { SidebarNavigation } from "../components/SidebarNavigation";
import { capsearchFetch, legacyUrl } from "../lib/capsearchAuth";

type RequestItem = {
  id: number;
  name: string | null;
  statusCatId: number | null;
  createdAt: string | null;
  updatedAt: string | null;
  totalRequirement: number | null;
  percentComplete: number | null;
};

type RequestsApiResponse = {
  items: RequestItem[];
};

const developmentClients = [
  "Joost - Capsearch",
  "Max - Capsearch",
  "Max - Capsearch Advisory Services",
  "Henk de Vries - 123Finance",
  "Maria de Jong - ABN Amro",
];

export default function RequestsPage() {
  const [items, setItems] = useState<RequestItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await capsearchFetch("/api/requests/my", { method: "GET" });
        if (!response.ok) {
          setError(`Kon aanvragen niet laden (HTTP ${response.status})`);
          setLoading(false);
          return;
        }

        const data = (await response.json()) as RequestsApiResponse;
        setItems(Array.isArray(data.items) ? data.items : []);
      } catch {
        setError("Netwerkfout bij het laden van aanvragen");
      } finally {
        setLoading(false);
      }
    };

    void load();

    const onSessionUpdated = () => {
      void load();
    };
    window.addEventListener("capsearch-session-updated", onSessionUpdated);

    return () => {
      window.removeEventListener("capsearch-session-updated", onSessionUpdated);
    };
  }, []);

  return (
    <main className="flex min-h-screen flex-col bg-[#f9f9f9] text-slate-900">
      <AuthSessionBridge />

      <header className="h-[60px] border-b border-[#d9535d] bg-[#ffffff]">
        <div className="flex h-full items-center justify-between gap-4 px-4">
          <div className="flex min-w-0 items-center gap-12">
            <a href={legacyUrl("dashboard")} aria-label="Capsearch dashboard" className="shrink-0">
              <Image
                src="/images/capsearch-logo-green.png"
                alt="Capsearch"
                width={200}
                height={38}
                className="h-auto w-[175px]"
                priority
              />
            </a>

            <nav aria-label="Top navigation" className="hidden md:block">
              <a
                href="#"
                className="whitespace-nowrap text-[15px] font-semibold text-[#6e6e6e] transition hover:text-[#505050]"
              >
                Aangesloten financiers
              </a>
            </nav>
          </div>

          <div className="flex shrink-0 items-center gap-3">
            <SessionControls developmentClients={developmentClients}>
              <button
                type="button"
                aria-label="CapWiki"
                className="flex h-8 w-8 items-center justify-center text-[#6a6258] transition hover:text-[#4e483f]"
              >
                <i aria-hidden="true" className="fab fa-wikipedia-w text-[18px] leading-none" />
              </button>

              <button
                type="button"
                aria-label="Registreer uren"
                className="flex h-7 w-7 items-center justify-center rounded-full bg-[#6d6a66] text-white transition hover:bg-[#585551]"
              >
                <i aria-hidden="true" className="fas fa-clock text-[14px] leading-none" />
              </button>

              <button
                type="button"
                aria-label="Inbox"
                className="flex h-8 w-8 items-center justify-center text-[#6d6a66] transition hover:text-[#4f4c48]"
              >
                <i aria-hidden="true" className="fas fa-envelope text-[18px] leading-none" />
              </button>
            </SessionControls>
          </div>
        </div>
      </header>

      <div className="flex min-h-0 flex-1">
        <aside className="flex w-[202px] shrink-0 flex-col border-r border-[#dcdcdc] bg-[#ebebeb] pt-[52px]">
          <SidebarNavigation currentPath="/requests" />
        </aside>

        <section className="flex min-w-0 flex-1 justify-center bg-[#f9f9f9]">
          <div className="w-full max-w-[1200px] px-6 py-6">
            <div className="mb-4">
              <h1 className="text-[18px] font-semibold text-black">Aanvragen</h1>
              <p className="mt-2 text-[13px] text-[#7a7f8f]">
                Demo-overzicht vanuit Next.js met JWT van de huidige gebruiker.
              </p>
            </div>

            <div className="overflow-hidden rounded-xl border border-slate-200 bg-white">
              <table className="min-w-full text-sm">
                <thead className="bg-slate-100 text-left text-slate-600">
                  <tr>
                    <th className="px-4 py-3 font-medium">ID</th>
                    <th className="px-4 py-3 font-medium">Naam</th>
                    <th className="px-4 py-3 font-medium">Status</th>
                    <th className="px-4 py-3 font-medium">Compleet</th>
                    <th className="px-4 py-3 font-medium">Bedrag</th>
                    <th className="px-4 py-3 font-medium">Laatste update</th>
                  </tr>
                </thead>
                <tbody>
                  {loading ? (
                    <tr>
                      <td className="px-4 py-6 text-slate-500" colSpan={6}>
                        Laden...
                      </td>
                    </tr>
                  ) : error ? (
                    <tr>
                      <td className="px-4 py-6 text-red-600" colSpan={6}>
                        {error}
                      </td>
                    </tr>
                  ) : items.length === 0 ? (
                    <tr>
                      <td className="px-4 py-6 text-slate-500" colSpan={6}>
                        Geen aanvragen gevonden.
                      </td>
                    </tr>
                  ) : (
                    items.map((item) => (
                      <tr key={item.id} className="border-t border-slate-100">
                        <td className="px-4 py-3">{item.id}</td>
                        <td className="px-4 py-3">{item.name || "-"}</td>
                        <td className="px-4 py-3">{item.statusCatId ?? "-"}</td>
                        <td className="px-4 py-3">{item.percentComplete ?? 0}%</td>
                        <td className="px-4 py-3">
                          {typeof item.totalRequirement === "number"
                            ? new Intl.NumberFormat("nl-NL", {
                                style: "currency",
                                currency: "EUR",
                                maximumFractionDigits: 0,
                              }).format(item.totalRequirement)
                            : "-"}
                        </td>
                        <td className="px-4 py-3">
                          {item.updatedAt
                            ? new Date(item.updatedAt).toLocaleString("nl-NL")
                            : item.createdAt
                              ? new Date(item.createdAt).toLocaleString("nl-NL")
                              : "-"}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
