"use client";

import { Plus, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { deletePosition } from "@/actions/positions";
import { Button } from "@/components/ui/Button";
import { useToast } from "@/components/ui/Toast";
import { fmtDate, todayIso } from "@/lib/format";
import type { OpenPositionResolved } from "@/lib/positions";
import { CreatePositionModal, type UnitOption } from "./CreatePositionModal";

type OpenPositionWithDays = OpenPositionResolved & { daysOpen: number };

type PositionsPageClientProps = {
  openPositions: OpenPositionWithDays[];
  units: UnitOption[];
};

export function PositionsPageClient({ openPositions, units }: PositionsPageClientProps) {
  const { showToast } = useToast();
  const router = useRouter();
  const [createOpen, setCreateOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const today = todayIso();

  async function handleDelete(id: string) {
    setDeletingId(id);
    const result = await deletePosition(id);
    setDeletingId(null);
    if (result.success) {
      showToast("Planstelle entfernt.");
      router.refresh();
    } else {
      showToast(result.error ?? "Fehler beim Löschen.", "error");
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="rounded border border-border bg-white p-4">
        <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
          <h2 className="text-sm font-bold text-ink">Unbesetzte Planstellen ({openPositions.length})</h2>
          <Button onClick={() => setCreateOpen(true)}>
            <Plus className="h-4 w-4" />
            Planstelle anlegen
          </Button>
        </div>
        {openPositions.length === 0 ? (
          <p className="text-sm text-ink-muted">Derzeit ist jede Planstelle besetzt.</p>
        ) : (
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {openPositions.map((p) => {
              const notYetValid = p.valid_from > today;
              return (
                <div key={p.id} className="flex flex-col rounded border border-border p-3">
                  <div className="flex items-start justify-between gap-2">
                    <div className="text-sm font-semibold text-ink">{p.title}</div>
                    <Button
                      variant="icon"
                      onClick={() => handleDelete(p.id)}
                      pending={deletingId === p.id}
                      aria-label={`Planstelle ${p.position_number} (${p.title}) entfernen`}
                      className="-mr-1 -mt-1 hover:!text-danger-solid"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                  <div className="text-xs text-ink-muted">
                    {p.position_number} · {p.orgLabel}
                  </div>
                  <div className="mt-1 text-xs text-ink-muted">
                    {p.is_chief ? "Leitungsplanstelle · " : ""}
                    seit {p.daysOpen} Tagen unbesetzt
                  </div>
                  {p.managerName && <div className="text-xs text-ink-muted">berichtet an {p.managerName}</div>}
                  {notYetValid && <div className="mt-1 text-xs font-semibold text-warning-text">Gültig ab {fmtDate(p.valid_from)}</div>}
                </div>
              );
            })}
          </div>
        )}
      </div>

      <CreatePositionModal open={createOpen} onClose={() => setCreateOpen(false)} units={units} />
    </div>
  );
}
