"use client";

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

type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];

export function RehirePanel({ open, onClose, employee }: { open: boolean; onClose: () => void; employee: EmployeeRow }) {
  const { showToast } = useToast();
  const router = useRouter();
  const [rehireDate, setRehireDate] = useState("");
  const [pending, setPending] = useState(false);

  async function handleSubmit() {
    if (!rehireDate) {
      showToast("Bitte ein Wiedereintrittsdatum angeben.", "error");
      return;
    }
    setPending(true);
    const result = await rehireEmployee({ employee_id: employee.id, rehire_date: rehireDate });
    setPending(false);
    if (result.success) {
      showToast(`${employee.first_name} ${employee.last_name} wurde wiedereingestellt.`);
      router.refresh();
      onClose();
    } else {
      showToast(result.error ?? "Fehler beim Speichern.", "error");
    }
  }

  return (
    <SlideOver
      open={open}
      onClose={onClose}
      title="Wiedereinstellung"
      subtitle={`${employee.first_name} ${employee.last_name}`}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>
            Abbrechen
          </Button>
          <Button onClick={handleSubmit} pending={pending}>
            Wiedereinstellen
          </Button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <div className="rounded border border-border bg-surface p-3 text-sm">
          <p className="text-xs font-semibold uppercase tracking-wide text-ink-muted">Letzte Position</p>
          <p className="mt-1 text-ink">{employee.job_title}</p>
          <p className="text-xs text-ink-muted">Ausgetreten am {fmtDate(employee.exit_date)}</p>
        </div>
        <TextField label="Wiedereintritt am" required type="date" value={rehireDate} onChange={setRehireDate} />
      </div>
    </SlideOver>
  );
}
