"use client";

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

import { apiFetch, todayString } from "@/lib/api";
import { validateReservationContactForm } from "@/lib/contactValidation";
import { ReservationSource, ReservationStatus, Venue, VenueBookingSettings } 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 NewReservationPage() {
  const router = useRouter();
  const [venues, setVenues] = useState<Venue[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [form, setForm] = useState({
    venue_id: "",
    customer_name: "",
    customer_phone: "",
    customer_email: "",
    reservation_date: todayString(),
    start_time: "20:00",
    duration_minutes: "120",
    guests: "2",
    status: "confirmed",
    source: "manual",
    notes: "",
    area_preference: ""
  });

  useEffect(() => {
    async function loadVenues() {
      try {
        const result = await apiFetch<Venue[]>("/venues");
        setVenues(result);
        const defaultVenue = result[0];
        if (defaultVenue) {
          setForm((current) => ({ ...current, venue_id: String(defaultVenue.id) }));
        }
      } catch (err) {
        setMessage(err instanceof Error ? err.message : "Impossibile caricare i locali");
      }
    }

    void loadVenues();
  }, []);

  useEffect(() => {
    async function loadBookingSettings() {
      if (!form.venue_id) {
        return;
      }

      try {
        const settings = await apiFetch<VenueBookingSettings>(`/booking-settings?venue_id=${form.venue_id}`);
        setForm((current) => {
          if (current.venue_id !== String(settings.venue_id)) {
            return current;
          }
          return {
            ...current,
            duration_minutes: String(settings.turn_duration_minutes)
          };
        });
      } catch (err) {
        setMessage(err instanceof Error ? err.message : "Impossibile caricare la durata turno");
      }
    }

    void loadBookingSettings();
  }, [form.venue_id]);

  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;
    }

    setLoading(true);

    try {
      await apiFetch("/reservations", {
        method: "POST",
        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 creare la prenotazione");
    } finally {
      setLoading(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">Nuova richiesta</p>
            <h2 className="mt-3 font-display text-4xl text-ink">Nuova prenotazione</h2>
            <p className="mt-3 section-intro">
              Inserisci i dati essenziali del cliente e prepara il servizio in modo ordinato fin dal primo passaggio.
            </p>
          </div>
          <Link href="/reservations" className="button-secondary">
            Indietro
          </Link>
        </div>

        <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={loading} type="submit">
              {loading ? "Salvataggio..." : "Salva prenotazione"}
            </button>
          </div>
        </form>
      </section>

      <aside className="panel">
        <p className="section-kicker">Linee guida</p>
        <h3 className="mt-3 font-display text-3xl text-ink">Inserimento rapido</h3>
        <div className="mt-4 space-y-4 text-sm leading-6 text-stone-600">
          <div className="soft-card">
            Conferma sempre data, ora e numero coperti prima del salvataggio: sono i dati che aiutano il team a
            preparare il tavolo giusto.
          </div>
          <div className="soft-card">
            Usa il canale corretto per distinguere arrivi manuali, richieste dal sito e flussi provenienti da
            WhatsApp.
          </div>
          <div className="soft-card">
            Compila la preferenza area solo quando ha un impatto reale sul servizio, altrimenti lascia il sistema piu
            libero di trovare la soluzione migliore.
          </div>
        </div>
      </aside>
    </main>
  );
}
