"use client";

import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import { apiFetch } from "@/lib/api";
import { validateReservationContactForm } from "@/lib/contactValidation";
import { Reservation, ReservationSource, ReservationStatus, Venue } from "@/lib/types";

const sources: ReservationSource[] = ["manual", "whatsapp", "web"];
const statuses: ReservationStatus[] = ["pending", "confirmed", "seated", "completed", "cancelled", "no_show"];
const sourceLabels: Record<ReservationSource, string> = {
  manual: "Manuale",
  whatsapp: "WhatsApp",
  web: "Sito web"
};

export default function EditReservationPage() {
  const router = useRouter();
  const params = useParams<{ reservationId: string }>();
  const reservationId = Number(params.reservationId);
  const [venues, setVenues] = useState<Venue[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [form, setForm] = useState({
    venue_id: "",
    customer_name: "",
    customer_phone: "",
    customer_email: "",
    reservation_date: "",
    start_time: "",
    duration_minutes: "120",
    guests: "2",
    status: "confirmed",
    source: "manual",
    notes: "",
    area_preference: ""
  });

  useEffect(() => {
    async function loadData() {
      setLoading(true);
      setMessage(null);
      try {
        const [venueResponse, reservation] = await Promise.all([
          apiFetch<Venue[]>("/venues"),
          apiFetch<Reservation>(`/reservations/${reservationId}`)
        ]);
        setVenues(venueResponse);
        setForm({
          venue_id: String(reservation.venue_id),
          customer_name: reservation.customer.name,
          customer_phone: reservation.customer.phone,
          customer_email: reservation.customer.email || "",
          reservation_date: reservation.reservation_date,
          start_time: reservation.start_time.slice(0, 5),
          duration_minutes: String(reservation.duration_minutes),
          guests: String(reservation.guests),
          status: reservation.status,
          source: reservation.source,
          notes: reservation.notes || "",
          area_preference: reservation.area_preference || ""
        });
      } catch (err) {
        setMessage(err instanceof Error ? err.message : "Impossibile caricare la prenotazione");
      } finally {
        setLoading(false);
      }
    }

    if (Number.isFinite(reservationId)) {
      void loadData();
    } else {
      setMessage("Prenotazione non valida");
      setLoading(false);
    }
  }, [reservationId]);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setMessage(null);

    let validatedContact: { customerPhone: string; customerEmail: string | null };
    try {
      validatedContact = validateReservationContactForm({
        customerPhone: form.customer_phone,
        customerEmail: form.customer_email,
      });
    } catch (err) {
      setMessage(err instanceof Error ? err.message : "Verifica telefono ed email prima di salvare.");
      return;
    }

    setSaving(true);

    try {
      await apiFetch<Reservation>(`/reservations/${reservationId}`, {
        method: "PUT",
        body: JSON.stringify({
          venue_id: Number(form.venue_id),
          customer_name: form.customer_name,
          customer_phone: validatedContact.customerPhone,
          customer_email: validatedContact.customerEmail,
          reservation_date: form.reservation_date,
          start_time: form.start_time,
          duration_minutes: Number(form.duration_minutes),
          guests: Number(form.guests),
          status: form.status,
          source: form.source,
          notes: form.notes || null,
          area_preference: form.area_preference || null
        })
      });
      router.push("/reservations");
    } catch (err) {
      setMessage(err instanceof Error ? err.message : "Impossibile aggiornare la prenotazione");
    } finally {
      setSaving(false);
    }
  }

  return (
    <main className="grid gap-6 xl:grid-cols-[1.15fr,0.85fr]">
      <section className="panel">
        <div className="mb-6 flex items-start justify-between gap-4">
          <div>
            <p className="section-kicker">Modifica prenotazione</p>
            <h2 className="mt-3 font-display text-4xl text-ink">Aggiorna i dettagli</h2>
            <p className="mt-3 section-intro">
              Correggi rapidamente cliente, orario, coperti e note senza uscire dalla regia prenotazioni.
            </p>
          </div>
          <Link href="/reservations" className="button-secondary">
            Indietro
          </Link>
        </div>

        {loading ? <p className="text-sm text-stone-500">Caricamento prenotazione...</p> : null}

        {!loading ? (
          <form className="grid gap-4 md:grid-cols-2" onSubmit={(event) => void handleSubmit(event)}>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Locale</span>
              <select className="field" value={form.venue_id} onChange={(e) => setForm({ ...form, venue_id: e.target.value })} required>
                <option value="">Seleziona locale</option>
                {venues.map((venue) => (
                  <option key={venue.id} value={venue.id}>
                    {venue.name}
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Nome cliente</span>
              <input className="field" value={form.customer_name} onChange={(e) => setForm({ ...form, customer_name: e.target.value })} required />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Telefono</span>
              <input
                className="field"
                type="tel"
                inputMode="tel"
                autoComplete="tel"
                value={form.customer_phone}
                onChange={(e) => setForm({ ...form, customer_phone: e.target.value })}
                required
              />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Email</span>
              <input
                className="field"
                type="email"
                autoComplete="email"
                value={form.customer_email}
                onChange={(e) => setForm({ ...form, customer_email: e.target.value })}
              />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Data</span>
              <input className="field" type="date" value={form.reservation_date} onChange={(e) => setForm({ ...form, reservation_date: e.target.value })} required />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Ora</span>
              <input className="field" type="time" value={form.start_time} onChange={(e) => setForm({ ...form, start_time: e.target.value })} required />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Durata turno (minuti)</span>
              <input className="field" type="number" min="30" step="15" value={form.duration_minutes} onChange={(e) => setForm({ ...form, duration_minutes: e.target.value })} required />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Coperti</span>
              <input className="field" type="number" min="1" value={form.guests} onChange={(e) => setForm({ ...form, guests: e.target.value })} required />
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Stato</span>
              <select className="field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                {statuses.map((status) => (
                  <option key={status} value={status}>
                    {status}
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Canale</span>
              <select className="field" value={form.source} onChange={(e) => setForm({ ...form, source: e.target.value })}>
                {sources.map((source) => (
                  <option key={source} value={source}>
                    {sourceLabels[source]}
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="mb-2 block text-sm text-stone-600">Preferenza area</span>
              <input className="field" value={form.area_preference} onChange={(e) => setForm({ ...form, area_preference: e.target.value })} />
            </label>
            <label className="block md:col-span-2">
              <span className="mb-2 block text-sm text-stone-600">Note</span>
              <textarea className="field min-h-32" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
            </label>

            {message ? <p className="notice is-error md:col-span-2">{message}</p> : null}

            <div className="md:col-span-2 flex justify-end">
              <button className="button-primary min-w-48" disabled={saving} type="submit">
                {saving ? "Salvataggio..." : "Aggiorna prenotazione"}
              </button>
            </div>
          </form>
        ) : null}
      </section>

      <aside className="panel">
        <p className="section-kicker">Controllo rapido</p>
        <h3 className="mt-3 font-display text-3xl text-ink">Cosa puoi cambiare</h3>
        <div className="mt-4 space-y-4 text-sm leading-6 text-stone-600">
          <div className="soft-card">
            Modifica nome, telefono, data, orario e coperti quando il cliente chiama o scrive per aggiornare la richiesta.
          </div>
          <div className="soft-card">
            Se cambi data, orario o numero di persone, il sistema ricalcola automaticamente l'assegnazione del tavolo.
          </div>
          <div className="soft-card">
            Usa lo stato per allineare sala e accoglienza quando la prenotazione e confermata, arrivata o chiusa.
          </div>
        </div>
      </aside>
    </main>
  );
}
