"use client";

import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { transferEmployee } from "@/actions/employees";
import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast";
import type { Database } from "@/lib/supabase/types";

type EmployeeRow = Database["public"]["Views"]["employees_directory"]["Row"];
type Division = Database["public"]["Tables"]["divisions"]["Row"];
type Department = Database["public"]["Tables"]["departments"]["Row"];
type Team = Database["public"]["Tables"]["teams"]["Row"];

type TransferPanelProps = {
  open: boolean;
  onClose: () => void;
  employee: EmployeeRow;
  divisions: Division[];
  departments: Department[];
  teams: Team[];
  currentTeamId: string | null;
};

export function TransferPanel({ open, onClose, employee, divisions, departments, teams, currentTeamId }: TransferPanelProps) {
  const { showToast } = useToast();
  const router = useRouter();
  const [effectiveDate, setEffectiveDate] = useState("");
  const [divisionId, setDivisionId] = useState(employee.division_id);
  const [teamId, setTeamId] = useState(currentTeamId ?? "");
  const [newTitle, setNewTitle] = useState("");
  const [pending, setPending] = useState(false);

  const teamsInDivision = useMemo(() => {
    const deptIds = new Set(departments.filter((d) => d.division_id === divisionId).map((d) => d.id));
    return teams.filter((t) => deptIds.has(t.department_id));
  }, [departments, teams, divisionId]);

  async function handleSubmit() {
    if (!effectiveDate || !teamId) {
      showToast("Bitte Datum und Zielteam angeben.", "error");
      return;
    }
    setPending(true);
    const result = await transferEmployee({
      employee_id: employee.id,
      effective_date: effectiveDate,
      new_team_id: teamId,
      new_title: newTitle || undefined,
    });
    setPending(false);
    if (result.success) {
      showToast(`${employee.first_name} ${employee.last_name} wurde versetzt.`);
      router.refresh();
      onClose();
    } else {
      showToast(result.error ?? "Fehler beim Speichern.", "error");
    }
  }

  return (
    <SlideOver
      open={open}
      onClose={onClose}
      title="Versetzung"
      subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`}
      footer={
        <>
          <button onClick={onClose} className="rounded px-4 py-2 text-sm font-semibold text-ink-body hover:bg-surface">
            Abbrechen
          </button>
          <button
            onClick={handleSubmit}
            disabled={pending}
            className="rounded bg-brand-500 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
          >
            Versetzen
          </button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <div>
          <label className="mb-1 block text-sm font-semibold text-ink">Wirksam ab*</label>
          <input
            type="date"
            value={effectiveDate}
            onChange={(e) => setEffectiveDate(e.target.value)}
            className="w-full rounded border border-border px-3 py-2 text-sm"
          />
        </div>
        <div>
          <label className="mb-1 block text-sm font-semibold text-ink">Neuer Bereich*</label>
          <select
            value={divisionId}
            onChange={(e) => {
              setDivisionId(e.target.value);
              setTeamId("");
            }}
            className="w-full rounded border border-border px-3 py-2 text-sm"
          >
            {divisions.map((d) => (
              <option key={d.id} value={d.id}>
                {d.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="mb-1 block text-sm font-semibold text-ink">Neues Team*</label>
          <select value={teamId} onChange={(e) => setTeamId(e.target.value)} className="w-full rounded border border-border px-3 py-2 text-sm">
            <option value="">Bitte wählen…</option>
            {teamsInDivision.map((t) => (
              <option key={t.id} value={t.id}>
                {t.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="mb-1 block text-sm font-semibold text-ink">Neuer Titel (optional)</label>
          <input
            value={newTitle}
            onChange={(e) => setNewTitle(e.target.value)}
            placeholder={employee.job_title}
            className="w-full rounded border border-border px-3 py-2 text-sm"
          />
        </div>
        <p className="text-xs text-ink-muted">Die neue Führungskraft wird automatisch anhand des Zielteams bestimmt.</p>
      </div>
    </SlideOver>
  );
}
