"use client";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";
import type { Case, Appointment } from "@/lib/types";
import { Breadcrumb } from "@/components/layout/Breadcrumb";
import { useState } from "react";
import { toast } from "sonner";

const APPOINTMENT_TYPES = [
  { value: "hearing", label: "Verhandlung" },
  { value: "meeting", label: "Besprechung" },
  { value: "consultation", label: "Beratung" },
  { value: "deadline_hearing", label: "Fristanhoerung" },
  { value: "other", label: "Sonstiges" },
];

const inputClass =
  "w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400";
const labelClass = "mb-1 block text-xs font-medium text-neutral-600";

export default function NewAppointmentPage() {
  const router = useRouter();
  const queryClient = useQueryClient();

  const [caseId, setCaseId] = useState("");
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [startAt, setStartAt] = useState("");
  const [endAt, setEndAt] = useState("");
  const [location, setLocation] = useState("");
  const [appointmentType, setAppointmentType] = useState("");

  const { data: casesData } = useQuery({
    queryKey: ["cases"],
    queryFn: () => api.get<{ cases: Case[]; total: number } | Case[]>("/cases"),
  });

  const cases = Array.isArray(casesData)
    ? casesData
    : Array.isArray(casesData?.cases)
      ? casesData.cases
      : [];

  const createMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      api.post<Appointment>("/appointments", body),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["appointments"] });
      queryClient.invalidateQueries({ queryKey: ["dashboard"] });
      toast.success("Termin erstellt");
      router.push(`/termine/${data.id}`);
    },
    onError: () => toast.error("Fehler beim Erstellen des Termins"),
  });

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!title.trim() || !startAt) return;

    const body: Record<string, unknown> = {
      title: title.trim(),
      start_at: new Date(startAt).toISOString(),
    };
    if (description.trim()) body.description = description.trim();
    if (endAt) body.end_at = new Date(endAt).toISOString();
    if (location.trim()) body.location = location.trim();
    if (appointmentType) body.appointment_type = appointmentType;
    if (caseId) body.case_id = caseId;

    createMutation.mutate(body);
  }

  return (
    <div className="animate-fade-in">
      <Breadcrumb
        items={[
          { label: "Dashboard", href: "/dashboard" },
          { label: "Termine", href: "/termine" },
          { label: "Neuer Termin" },
        ]}
      />

      <h1 className="text-lg font-semibold text-neutral-900">
        Neuer Termin
      </h1>
      <p className="mt-0.5 text-sm text-neutral-500">
        Erstellen Sie einen neuen Termin.
      </p>

      <form
        onSubmit={handleSubmit}
        className="mt-6 max-w-lg space-y-4 rounded-lg border border-neutral-200 bg-white p-5"
      >
        <div>
          <label className={labelClass}>Titel *</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            className={inputClass}
            placeholder="z.B. Muendliche Verhandlung"
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Beginn *</label>
            <input
              type="datetime-local"
              value={startAt}
              onChange={(e) => setStartAt(e.target.value)}
              required
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Ende</label>
            <input
              type="datetime-local"
              value={endAt}
              onChange={(e) => setEndAt(e.target.value)}
              className={inputClass}
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Typ</label>
            <select
              value={appointmentType}
              onChange={(e) => setAppointmentType(e.target.value)}
              className={inputClass}
            >
              <option value="">Kein Typ</option>
              {APPOINTMENT_TYPES.map((t) => (
                <option key={t.value} value={t.value}>
                  {t.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className={labelClass}>Akte (optional)</label>
            <select
              value={caseId}
              onChange={(e) => setCaseId(e.target.value)}
              className={inputClass}
            >
              <option value="">Keine Akte</option>
              {cases.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.case_number} — {c.title}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className={labelClass}>Ort</label>
          <input
            type="text"
            value={location}
            onChange={(e) => setLocation(e.target.value)}
            className={inputClass}
            placeholder="z.B. UPC Muenchen, Saal 3"
          />
        </div>

        <div>
          <label className={labelClass}>Beschreibung</label>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={3}
            className={inputClass}
            placeholder="Optionale Beschreibung zum Termin"
          />
        </div>

        <div className="flex items-center justify-end gap-2 pt-2">
          <button
            type="button"
            onClick={() => router.push("/termine")}
            className="rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-50"
          >
            Abbrechen
          </button>
          <button
            type="submit"
            disabled={
              createMutation.isPending || !title.trim() || !startAt
            }
            className="rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
          >
            {createMutation.isPending ? "Erstellen..." : "Termin anlegen"}
          </button>
        </div>
      </form>
    </div>
  );
}
