"use client";

import { Plus } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useHireWizard } from "@/components/hire/HireWizardContext";
import type { OpenPositionResolved } from "@/lib/positions";
import { CreatePositionModal } from "./CreatePositionModal";
import { StaffInternallyModal } from "./StaffInternallyModal";

type Team = {
  id: string;
  org_number: string;
  name: string;
  lead: { id: string; name: string } | null;
  headcount: number;
  fte: number;
  openCount: number;
};
type Department = { id: string; org_number: string; name: string; teams: Team[] };
type DivisionCard = {
  id: string;
  org_number: string;
  name: string;
  head: { id: string; name: string } | null;
  headcount: number;
  departments: Department[];
};
type OpenPositionWithDays = OpenPositionResolved & { daysOpen: number };

type PositionsPageClientProps = {
  openPositions: OpenPositionWithDays[];
  divisionCards: DivisionCard[];
  teams: { id: string; org_number: string; name: string; department_id: string }[];
};

export function PositionsPageClient({ openPositions, divisionCards, teams }: PositionsPageClientProps) {
  const { openWizard } = useHireWizard();
  const [createOpen, setCreateOpen] = useState(false);
  const [staffTarget, setStaffTarget] = useState<{ id: string; title: string; is_lead: boolean } | null>(null);

  return (
    <div className="flex flex-col gap-6">
      <div className="rounded border border-border bg-white p-4">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="text-sm font-bold text-ink">Offene Positionen ({openPositions.length})</h2>
          <button
            type="button"
            onClick={() => setCreateOpen(true)}
            className="flex items-center gap-1.5 rounded bg-brand-500 px-3 py-1.5 text-sm font-semibold text-white hover:bg-brand-600"
          >
            <Plus className="h-4 w-4" />
            Position ausschreiben
          </button>
        </div>
        {openPositions.length === 0 ? (
          <p className="text-sm text-ink-muted">Derzeit keine offenen Positionen.</p>
        ) : (
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {openPositions.map((p) => (
              <div key={p.id} className="rounded border border-border p-3">
                <div className="text-sm font-semibold text-ink">{p.title}</div>
                <div className="text-xs text-ink-muted">
                  {p.position_number} · {p.orgLabel}
                </div>
                <div className="mt-1 text-xs text-ink-muted">seit {p.daysOpen} Tagen offen</div>
                <div className="mt-3 flex gap-2">
                  <button
                    type="button"
                    onClick={() => setStaffTarget({ id: p.id, title: p.title, is_lead: p.is_lead })}
                    className="flex-1 rounded bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-600"
                  >
                    Intern
                  </button>
                  <button
                    type="button"
                    onClick={() => openWizard({ positionId: p.id })}
                    className="flex-1 rounded border border-border px-3 py-1.5 text-xs font-semibold text-ink-body hover:bg-surface"
                  >
                    Extern
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {divisionCards.map((div) => (
        <div key={div.id} className="rounded border border-border bg-white p-4">
          <div className="mb-3 flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3">
            <div>
              <div className="text-xs text-ink-muted">{div.org_number}</div>
              <div className="text-sm font-bold text-ink">{div.name}</div>
              {div.head && (
                <Link href={`/employees/${div.head.id}`} className="text-xs text-brand-700 hover:underline">
                  {div.head.name}
                </Link>
              )}
            </div>
            <div className="text-sm font-semibold text-ink">{div.headcount} Mitarbeiter:innen</div>
          </div>
          <div className="flex flex-col gap-4">
            {div.departments.map((dept) => (
              <div key={dept.id}>
                <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">
                  {dept.org_number} · {dept.name}
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[600px] text-sm">
                    <thead>
                      <tr className="text-left text-xs text-ink-muted">
                        <th className="py-1 pr-3">Team</th>
                        <th className="py-1 pr-3">Teamleitung</th>
                        <th className="py-1 pr-3">Headcount</th>
                        <th className="py-1 pr-3">FTE</th>
                        <th className="py-1 pr-3">Offen</th>
                      </tr>
                    </thead>
                    <tbody>
                      {dept.teams.map((team) => (
                        <tr key={team.id} className="border-t border-border">
                          <td className="py-1.5 pr-3">
                            <div className="text-ink">{team.name}</div>
                            <div className="text-xs text-ink-muted">{team.org_number}</div>
                          </td>
                          <td className="py-1.5 pr-3 text-ink-body">
                            {team.lead ? (
                              <Link href={`/employees/${team.lead.id}`} className="hover:text-brand-700 hover:underline">
                                {team.lead.name}
                              </Link>
                            ) : (
                              "–"
                            )}
                          </td>
                          <td className="py-1.5 pr-3 text-ink-body">{team.headcount}</td>
                          <td className="py-1.5 pr-3 text-ink-body">{team.fte.toFixed(1)}</td>
                          <td className="py-1.5 pr-3 font-semibold text-brand-700">{team.openCount || "–"}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}

      <CreatePositionModal open={createOpen} onClose={() => setCreateOpen(false)} teams={teams} />
      {staffTarget && (
        <StaffInternallyModal
          open={Boolean(staffTarget)}
          onClose={() => setStaffTarget(null)}
          positionId={staffTarget.id}
          positionTitle={staffTarget.title}
          isLead={staffTarget.is_lead}
        />
      )}
    </div>
  );
}
