"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import {
  initialApplicantsByPosition,
  initialPositions,
  readApplicantsFromStorage,
  readPositionsFromStorage,
  type Position,
} from "@/components/initialPositionsData";

type PositionsProps = {
  showHeader?: boolean;
};

export default function Positions({ showHeader = true }: PositionsProps) {
  const [positions, setPositions] = useState<Position[]>(initialPositions);
  const [applicantCountsByPosition, setApplicantCountsByPosition] = useState<Record<string, number>>(
    () =>
      initialPositions.reduce<Record<string, number>>((acc, position) => {
        acc[position.id] = (initialApplicantsByPosition[position.id] ?? []).length;
        return acc;
      }, {})
  );
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    const storedPositions = readPositionsFromStorage();
    const storedCounts = storedPositions.reduce<Record<string, number>>((acc, position) => {
      acc[position.id] = readApplicantsFromStorage(position.id).length;
      return acc;
    }, {});

    // Keep skeleton visible briefly so reset/remount feedback is noticeable.
    const timeout = window.setTimeout(() => {
      setPositions(storedPositions);
      setApplicantCountsByPosition(storedCounts);
      setIsLoading(false);
    }, 220);

    return () => {
      window.clearTimeout(timeout);
    };
  }, []);

  return (
    <section className="px-6 pb-10 pt-2 md:px-12 lg:px-20">
      {showHeader && (
        <div className="flex flex-col gap-3">
          <div>
            <h2 className="text-4xl font-bold text-slate-900">Your Positions</h2>
            <p className="mt-2 text-lg text-slate-600">
              Select a position to review and move applicants through the ATS workflow.
            </p>
          </div>
        </div>
      )}

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        {isLoading
          ? Array.from({ length: 4 }).map((_, index) => (
              <div
                key={`positions-skeleton-${index}`}
                className="rounded-xl border border-slate-200 bg-white p-5 animate-pulse"
              >
                <div className="mb-4 h-4 w-20 rounded bg-slate-200" />
                <div className="space-y-3">
                  <div className="h-7 w-3/4 rounded bg-slate-200" />
                  <div className="h-4 w-2/3 rounded bg-slate-200" />
                  <div className="h-4 w-1/2 rounded bg-slate-200" />
                  <div className="h-4 w-28 rounded bg-slate-200" />
                </div>
              </div>
            ))
          : positions.map((position) => (
              <article
                key={position.id}
                className="rounded-xl border border-slate-200 bg-white p-5 transition-colors hover:border-orange-300 hover:bg-orange-50/40"
              >
                <div className="mb-4 flex items-center justify-between">
                  <p className="text-sm font-semibold uppercase tracking-wide text-slate-500">
                    {position.id}
                  </p>
                  <span className="text-sm font-semibold text-orange-600">Open role</span>
                </div>

                <div className="grid gap-2">
                  <p className="text-2xl font-semibold text-slate-900">{position.title}</p>
                  <p className="text-sm text-slate-600">
                    {position.department} • {position.location}
                  </p>
                  <div className="flex items-center gap-2 text-sm text-slate-600">
                    <Link
                      href={`/positions/${position.id}`}
                      className="font-semibold text-slate-700 underline underline-offset-4"
                    >
                      {applicantCountsByPosition[position.id] ?? 0} applicant(s)
                    </Link>
                    <span>•</span>
                    <span>{position.employmentType}</span>
                  </div>
                  <Link
                    href={`/positions/${position.id}`}
                    className="pt-2 text-sm font-semibold text-slate-700 underline underline-offset-4"
                  >
                    View applicants
                  </Link>
                </div>
              </article>
            ))}
      </div>
    </section>
  );
}
