"use client";

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

type EmployeeRow = Database["public"]["Tables"]["employees"]["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 variant="ghost" onClick={onClose}>
            Abbrechen
          </Button>
          <Button onClick={handleSubmit} pending={pending}>
            Versetzen
          </Button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <TextField label="Wirksam ab" required type="date" value={effectiveDate} onChange={setEffectiveDate} />
        <SelectField
          label="Neuer Bereich"
          required
          value={divisionId}
          onChange={(v) => {
            setDivisionId(v);
            setTeamId("");
          }}
          options={divisions.map((d) => ({ value: d.id, label: d.name }))}
        />
        <SelectField
          label="Neues Team"
          required
          value={teamId}
          onChange={setTeamId}
          placeholder="Bitte wählen…"
          options={teamsInDivision.map((t) => ({ value: t.id, label: t.name }))}
        />
        <TextField
          label="Neuer Titel (optional)"
          value={newTitle}
          onChange={setNewTitle}
          placeholder={employee.job_title}
          hint="Die neue Führungskraft wird automatisch anhand des Zielteams bestimmt."
        />
      </div>
    </SlideOver>
  );
}
