"use client";

import { useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { addEmploymentRecordAction, deleteEmploymentRecordAction } from "@/lib/actions/team";
import {
  EMPLOYMENT_TYPES,
  EMPLOYMENT_TYPE_LABELS,
  EMPLOYMENT_TYPE_COLORS,
  TERMINATION_TYPES,
  TERMINATION_TYPE_LABELS,
  PROBATION_ELIGIBLE_TYPES,
  type EmploymentType,
  type TerminationType,
} from "@/lib/employment";
import { formatDateDE } from "@/lib/orderConstants";

// Diese beiden Arten sind Einzel-Ereignisse (ein Datum), keine laufenden
// Beschäftigungszeiträume — "Bis"/Probezeit ergeben für sie keinen Sinn.
const EVENT_TYPES: EmploymentType[] = ["termination", "note"];

type EmploymentRecord = {
  id: string;
  type: EmploymentType;
  startDate: string;
  endDate: string | null;
  probationMonths: number | null;
  terminationType: TerminationType | null;
  note: string;
};

const fmt = (d: string) => formatDateDE(new Date(d));

export function EmploymentRecordsPanel({ clientId, records }: { clientId: string; records: EmploymentRecord[] }) {
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();
  const [type, setType] = useState<EmploymentType>("employee");
  const [deletePending, startDeleteTransition] = useTransition();
  const formRef = useRef<HTMLFormElement>(null);
  const router = useRouter();

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      const result = await addEmploymentRecordAction(clientId, data);
      if (result?.error) {
        setError(result.error);
      } else {
        setError(null);
        form.reset();
        setType("employee");
        router.refresh();
      }
    });
  }

  const sorted = [...records].sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime());

  return (
    <div className="border border-white/10 rounded-xl p-5">
      <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-3">Personalakte</p>

      <form
        ref={formRef}
        onSubmit={(e) => {
          e.preventDefault();
          submit(e.currentTarget);
        }}
        className="flex flex-col gap-2.5 pb-4 mb-4 border-b border-white/10"
      >
        <label className="flex flex-col gap-1 text-[0.65rem]">
          <span className="text-[var(--rk-ink-muted)]">Art</span>
          <select
            name="type"
            value={type}
            onChange={(e) => setType(e.target.value as EmploymentType)}
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-white/50"
          >
            {EMPLOYMENT_TYPES.map((t) => (
              <option key={t} value={t}>
                {EMPLOYMENT_TYPE_LABELS[t]}
              </option>
            ))}
          </select>
        </label>
        {EVENT_TYPES.includes(type) ? (
          <label className="flex flex-col gap-1 text-[0.65rem] w-40">
            <span className="text-[var(--rk-ink-muted)]">Datum</span>
            <input
              name="startDate"
              type="date"
              required
              className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
            />
          </label>
        ) : (
          <div className="grid grid-cols-2 gap-2.5">
            <label className="flex flex-col gap-1 text-[0.65rem]">
              <span className="text-[var(--rk-ink-muted)]">Von</span>
              <input
                name="startDate"
                type="date"
                required
                className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
              />
            </label>
            <label className="flex flex-col gap-1 text-[0.65rem]">
              <span className="text-[var(--rk-ink-muted)]">Bis (leer = unbefristet)</span>
              <input
                name="endDate"
                type="date"
                className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
              />
            </label>
          </div>
        )}
        {PROBATION_ELIGIBLE_TYPES.includes(type as (typeof PROBATION_ELIGIBLE_TYPES)[number]) && (
          <label className="flex flex-col gap-1 text-[0.65rem] w-40">
            <span className="text-[var(--rk-ink-muted)]">Probezeit in Monaten (optional)</span>
            <input
              name="probationMonths"
              type="number"
              min="1"
              max="24"
              className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:border-white/50"
            />
          </label>
        )}
        {type === "termination" && (
          <label className="flex flex-col gap-1 text-[0.65rem]">
            <span className="text-[var(--rk-ink-muted)]">Kündigungsart</span>
            <select
              name="terminationType"
              defaultValue=""
              required
              className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-white/50"
            >
              <option value="" disabled>
                Bitte auswählen …
              </option>
              {TERMINATION_TYPES.map((t) => (
                <option key={t} value={t}>
                  {TERMINATION_TYPE_LABELS[t]}
                </option>
              ))}
            </select>
          </label>
        )}
        <label className="flex flex-col gap-1 text-[0.65rem]">
          <span className="text-[var(--rk-ink-muted)]">Bemerkung (optional)</span>
          <input
            name="note"
            placeholder="z. B. Grund, Vereinbarung, Besonderheiten"
            className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-xs focus:outline-none focus:border-white/50"
          />
        </label>
        <button
          type="submit"
          disabled={pending}
          className="self-start text-xs border border-white/30 rounded-lg px-3 py-1.5 hover:border-white disabled:opacity-50"
        >
          Eintrag hinzufügen
        </button>
        {error && <p className="text-xs text-red-400">{error}</p>}
      </form>

      {sorted.length === 0 ? (
        <p className="text-xs text-[var(--rk-ink-muted)]">Noch keine Einträge.</p>
      ) : (
        <div className="flex flex-col gap-2">
          {sorted.map((r) => (
            <div
              key={r.id}
              className="flex items-start justify-between gap-3 text-xs rounded-lg px-3 py-2.5"
              style={{
                backgroundColor: `${EMPLOYMENT_TYPE_COLORS[r.type]}14`,
                borderLeft: `3px solid ${EMPLOYMENT_TYPE_COLORS[r.type]}`,
              }}
            >
              <div>
                <p className="text-[var(--rk-ink)]">
                  <strong className="font-medium" style={{ color: EMPLOYMENT_TYPE_COLORS[r.type] }}>
                    {EMPLOYMENT_TYPE_LABELS[r.type]}
                  </strong>{" "}
                  — {fmt(r.startDate)}
                  {EVENT_TYPES.includes(r.type) ? "" : r.endDate ? ` bis ${fmt(r.endDate)}` : " (unbefristet)"}
                  {r.probationMonths ? ` · Probezeit ${r.probationMonths} Monate` : ""}
                  {r.terminationType ? ` · ${TERMINATION_TYPE_LABELS[r.terminationType]}` : ""}
                </p>
                {r.note && <p className="text-[var(--rk-ink-muted)] mt-0.5">{r.note}</p>}
              </div>
              <button
                type="button"
                disabled={deletePending}
                onClick={() => {
                  if (confirm("Diesen Eintrag wirklich löschen?")) {
                    startDeleteTransition(async () => {
                      await deleteEmploymentRecordAction(clientId, r.id);
                      router.refresh();
                    });
                  }
                }}
                className="text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50 shrink-0"
              >
                Löschen
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
