"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import Header from "@/components/Header";
import ApplicantsSection, { type StageMoveEvent } from "@/components/ApplicantsSection";
import {
  initializeEventStreamStorage,
  readEventsForPosition,
  type AtsEvent,
} from "@/components/eventStream";
import { formatEventForRecruiter } from "@/components/hrEventFormatter";
import {
  initializeAtsStorage,
  readPositionByIdFromStorage,
  type Position,
} from "@/components/initialPositionsData";

export default function PositionPage() {
  const params = useParams<{ id: string }>();
  const positionId = params?.id ?? "";
  const [position, setPosition] = useState<Position | null>(null);
  const [events, setEvents] = useState<AtsEvent[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  function refreshEvents() {
    setEvents(readEventsForPosition(positionId));
  }

  function handleApplicantStageMove(_event: StageMoveEvent) {
    void _event;
    refreshEvents();
  }

  function downloadAuditLog() {
    const fileName = `position-${positionId}-audit-log.json`;
    const json = JSON.stringify(events, null, 2);
    const blob = new Blob([json], { type: "application/json" });
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = fileName;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    window.URL.revokeObjectURL(url);
  }

  useEffect(() => {
    setIsLoading(true);
    initializeAtsStorage();
    initializeEventStreamStorage();
    setPosition(readPositionByIdFromStorage(positionId) ?? null);
    refreshEvents();
    setIsLoading(false);
  }, [positionId]);

  return (
    <div className="min-h-screen flex flex-col">
      <Header />

      <div className="min-h-screen bg-gradient-to-b from-orange-50 via-white to-white text-slate-900">
        <section className="px-6 pt-12 md:px-12 lg:px-20">
          <Link
            href="/"
            className="text-sm font-semibold text-slate-600 underline underline-offset-4 hover:text-slate-900"
          >
            Back to positions
          </Link>

          {isLoading ? (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6 animate-pulse">
              <div className="h-4 w-20 rounded bg-slate-200" />
              <div className="mt-3 h-10 w-2/3 rounded bg-slate-200" />
              <div className="mt-3 h-6 w-1/2 rounded bg-slate-200" />
              <div className="mt-2 h-4 w-1/3 rounded bg-slate-200" />
            </div>
          ) : position ? (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6">
              <p className="text-sm font-semibold uppercase tracking-wide text-slate-500">
                {position.id}
              </p>
              <h1 className="mt-2 text-4xl font-bold text-slate-900">{position.title}</h1>
              <p className="mt-2 text-lg text-slate-600">
                {position.department} • {position.location}
              </p>
              <p className="mt-1 text-sm text-slate-600">
                {position.openings} opening(s) • {position.employmentType}
              </p>
            </div>
          ) : (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6">
              <h1 className="text-2xl font-bold text-slate-900">Position not found</h1>
              <p className="mt-2 text-slate-600">
                This position id does not exist in LocalStorage.
              </p>
            </div>
          )}
        </section>

        {isLoading ? (
          <>
            <section className="px-6 pb-16 pt-10 md:px-12 lg:px-20">
              <div className="h-10 w-60 rounded bg-slate-200 animate-pulse" />
              <div className="mt-3 h-6 w-96 rounded bg-slate-200 animate-pulse" />
              <div className="mt-8 grid gap-4 xl:grid-cols-5 md:grid-cols-2">
                {Array.from({ length: 5 }).map((_, index) => (
                  <div
                    key={`position-page-kanban-skeleton-${index}`}
                    className="min-h-[380px] rounded-xl border border-slate-200 bg-white/70 p-4 animate-pulse"
                  >
                    <div className="h-7 w-2/3 rounded bg-slate-200" />
                    <div className="mt-2 h-4 w-5/6 rounded bg-slate-200" />
                    <div className="mt-4 space-y-3">
                      <div className="rounded-lg border bg-white p-3">
                        <div className="h-5 w-3/4 rounded bg-slate-200" />
                        <div className="mt-2 h-4 w-1/2 rounded bg-slate-200" />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </section>
            <section className="px-6 pb-16 pt-2 md:px-12 lg:px-20">
              <div className="h-10 w-44 rounded bg-slate-200 animate-pulse" />
              <div className="mt-3 h-6 w-80 rounded bg-slate-200 animate-pulse" />
              <div className="mt-6 rounded-xl border border-slate-200 bg-white p-4">
                <div className="h-5 w-1/3 rounded bg-slate-200 animate-pulse" />
                <div className="mt-3 h-4 w-2/3 rounded bg-slate-200 animate-pulse" />
                <div className="mt-2 h-4 w-1/2 rounded bg-slate-200 animate-pulse" />
              </div>
            </section>
          </>
        ) : position ? (
          <>
            <ApplicantsSection
              positionId={position.id}
              positionTitle={position.title}
              onApplicantStageMove={handleApplicantStageMove}
            />

            <section className="px-6 pb-16 pt-2 md:px-12 lg:px-20">
              <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
                <div>
                  <h2 className="text-4xl font-bold text-slate-900">Audit Log</h2>
                  <p className="mt-2 text-lg text-slate-600">
                    Hiring activity timeline for this position.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={downloadAuditLog}
                  className="h-11 rounded-md bg-slate-700 px-5 text-sm font-semibold text-white transition-colors hover:bg-slate-800"
                >
                  Download Audit Log
                </button>
              </div>

              <div className="mt-6 overflow-hidden rounded-xl border border-slate-200 bg-white">
                {events.length === 0 ? (
                  <p className="p-5 text-sm text-slate-600">No events found for this position.</p>
                ) : (
                  <ul className="divide-y divide-slate-200">
                    {events.map((event) => {
                      const formatted = formatEventForRecruiter(event);
                      const streamCategory =
                        typeof event.payload.streamCategory === "string"
                          ? event.payload.streamCategory
                          : "activity";

                      return (
                        <li key={event.eventId} className="p-4">
                          <p className="text-base font-semibold text-slate-900">{formatted.title}</p>
                          <p className="mt-1 text-sm text-slate-700">{formatted.detail}</p>
                          <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-slate-500">
                            <span className="rounded-full bg-slate-100 px-2 py-1">{streamCategory}</span>
                            <span>{new Date(event.occurredAt).toLocaleString()}</span>
                            <span className="font-mono">{event.eventId}</span>
                          </div>
                        </li>
                      );
                    })}
                  </ul>
                )}
              </div>
            </section>
          </>
        ) : null}
      </div>
    </div>
  );
}
