"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { rehireEmployee } from "@/actions/employees";
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 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"
          >
            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>
        <div>
          <label className="mb-1 block text-sm font-semibold text-ink">Wiedereintritt am*</label>
          <input
            type="date"
            value={rehireDate}
            onChange={(e) => setRehireDate(e.target.value)}
            className="w-full rounded border border-border px-3 py-2 text-sm"
          />
        </div>
      </div>
    </SlideOver>
  );
}
