"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { adjustKarenzReturn, recordKarenzReturn, startKarenz } from "@/actions/employees";
import { SegmentedControl } from "@/components/ui/SegmentedControl";
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"];
type Mode = "adjust" | "return";
type EmploymentMode = "unverändert" | "Vollzeit" | "Teilzeit";

export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClose: () => void; employee: EmployeeRow }) {
  const { showToast } = useToast();
  const router = useRouter();
  const isOnKarenz = employee.status === "Karenz";
  const [mode, setMode] = useState<Mode>("adjust");
  const [pending, setPending] = useState(false);

  const [karenzStart, setKarenzStart] = useState("");
  const [plannedReturn, setPlannedReturn] = useState("");
  const [startNote, setStartNote] = useState("");

  const [newReturnDate, setNewReturnDate] = useState(employee.karenz_return_date ?? "");
  const [adjustNote, setAdjustNote] = useState("");

  const [returnDate, setReturnDate] = useState("");
  const [employmentMode, setEmploymentMode] = useState<EmploymentMode>("unverändert");
  const [weeklyHours, setWeeklyHours] = useState("20");

  const diffDays =
    isOnKarenz && employee.karenz_return_date && newReturnDate
      ? Math.round((new Date(newReturnDate).getTime() - new Date(employee.karenz_return_date).getTime()) / 86400000)
      : 0;

  async function handleStart() {
    if (!karenzStart || !plannedReturn) {
      showToast("Bitte beide Daten angeben.", "error");
      return;
    }
    setPending(true);
    const result = await startKarenz({ employee_id: employee.id, karenz_start_date: karenzStart, planned_return_date: plannedReturn, note: startNote });
    setPending(false);
    if (result.success) {
      showToast("Karenz erfasst.");
      router.refresh();
      onClose();
    } else {
      showToast(result.error ?? "Fehler.", "error");
    }
  }

  async function handleAdjust() {
    if (!newReturnDate || newReturnDate === employee.karenz_return_date) {
      showToast("Bitte ein neues Rückkehrdatum angeben.", "error");
      return;
    }
    if (new Date(newReturnDate) <= new Date()) {
      showToast("Rückkehrdatum muss in der Zukunft liegen.", "error");
      return;
    }
    setPending(true);
    const result = await adjustKarenzReturn({ employee_id: employee.id, new_return_date: newReturnDate, note: adjustNote });
    setPending(false);
    if (result.success) {
      showToast("Rückkehrdatum angepasst.");
      router.refresh();
      onClose();
    } else {
      showToast(result.error ?? "Fehler.", "error");
    }
  }

  async function handleReturn() {
    if (!returnDate) {
      showToast("Bitte Rückkehrdatum angeben.", "error");
      return;
    }
    if (employmentMode === "Teilzeit" && (Number(weeklyHours) <= 0 || Number(weeklyHours) >= 38.5)) {
      showToast("Wochenstunden müssen zwischen 0 und 38,5 liegen.", "error");
      return;
    }
    setPending(true);
    const result = await recordKarenzReturn({
      employee_id: employee.id,
      return_date: returnDate,
      employment_mode: employmentMode,
      weekly_hours: employmentMode === "Teilzeit" ? Number(weeklyHours) : undefined,
    });
    setPending(false);
    if (result.success) {
      showToast("Wiedereintritt erfasst.");
      router.refresh();
      onClose();
    } else {
      showToast(result.error ?? "Fehler.", "error");
    }
  }

  return (
    <SlideOver
      open={open}
      onClose={onClose}
      title={isOnKarenz ? "Karenz verwalten" : "Karenz"}
      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>
          {!isOnKarenz && (
            <button onClick={handleStart} disabled={pending} className="rounded bg-warning-text px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">
              Karenz erfassen
            </button>
          )}
          {isOnKarenz && mode === "adjust" && (
            <button onClick={handleAdjust} disabled={pending} className="rounded bg-warning-text px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">
              Speichern
            </button>
          )}
          {isOnKarenz && mode === "return" && (
            <button onClick={handleReturn} disabled={pending} className="rounded bg-warning-text px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">
              Wiedereintritt erfassen
            </button>
          )}
        </>
      }
    >
      {!isOnKarenz && (
        <div className="flex flex-col gap-4">
          <div>
            <label className="mb-1 block text-sm font-semibold text-ink">Karenzbeginn*</label>
            <input type="date" value={karenzStart} onChange={(e) => setKarenzStart(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">Geplante Rückkehr*</label>
            <input type="date" value={plannedReturn} onChange={(e) => setPlannedReturn(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">Anmerkung</label>
            <textarea value={startNote} onChange={(e) => setStartNote(e.target.value)} rows={3} className="w-full rounded border border-border px-3 py-2 text-sm" />
          </div>
        </div>
      )}

      {isOnKarenz && (
        <div className="flex flex-col gap-4">
          <SegmentedControl<Mode>
            value={mode}
            onChange={setMode}
            options={[
              { value: "adjust", label: "Rückkehr anpassen" },
              { value: "return", label: "Wiedereintritt erfassen" },
            ]}
          />

          {mode === "adjust" && (
            <>
              <p className="text-sm text-ink-muted">Aktuelles Rückkehrdatum: {fmtDate(employee.karenz_return_date)}</p>
              <div>
                <label className="mb-1 block text-sm font-semibold text-ink">Neues Rückkehrdatum*</label>
                <input
                  type="date"
                  value={newReturnDate}
                  onChange={(e) => setNewReturnDate(e.target.value)}
                  className="w-full rounded border border-border px-3 py-2 text-sm"
                />
              </div>
              {diffDays !== 0 && (
                <div className={`rounded px-3 py-2 text-sm ${diffDays > 0 ? "bg-warning-bg text-warning-text" : "bg-success-bg text-success-text"}`}>
                  {diffDays > 0 ? `Verlängerung um ${diffDays} Tage` : `Verkürzung um ${Math.abs(diffDays)} Tage`}
                </div>
              )}
              <div>
                <label className="mb-1 block text-sm font-semibold text-ink">Grund/Anmerkung</label>
                <textarea value={adjustNote} onChange={(e) => setAdjustNote(e.target.value)} rows={3} className="w-full rounded border border-border px-3 py-2 text-sm" />
              </div>
            </>
          )}

          {mode === "return" && (
            <>
              <div>
                <label className="mb-1 block text-sm font-semibold text-ink">Rückkehrdatum*</label>
                <input type="date" value={returnDate} onChange={(e) => setReturnDate(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">Beschäftigungsausmaß</label>
                <select
                  value={employmentMode}
                  onChange={(e) => setEmploymentMode(e.target.value as EmploymentMode)}
                  className="w-full rounded border border-border px-3 py-2 text-sm"
                >
                  <option value="unverändert">unverändert</option>
                  <option value="Vollzeit">Vollzeit (38,5h)</option>
                  <option value="Teilzeit">Teilzeit-Elternteilzeit</option>
                </select>
              </div>
              {employmentMode === "Teilzeit" && (
                <div>
                  <label className="mb-1 block text-sm font-semibold text-ink">Wochenstunden (unter 38,5)*</label>
                  <input
                    type="number"
                    step="0.5"
                    max="38"
                    value={weeklyHours}
                    onChange={(e) => setWeeklyHours(e.target.value)}
                    className="w-full rounded border border-border px-3 py-2 text-sm"
                  />
                </div>
              )}
            </>
          )}
        </div>
      )}
    </SlideOver>
  );
}
