"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { TextareaHTMLAttributes } from "react";

import { apiFetch } from "@/lib/api";
import {
  VenueBookingSettings,
  WhatsAppConfigValidation,
  WhatsAppEventLog,
  WhatsAppSendTestResponse,
  WhatsAppStatus
} from "@/lib/types";

const defaultMessage =
  "Ciao, ti confermiamo la tua prenotazione. Se hai bisogno di modifiche, rispondi pure a questo messaggio.";

function formatEventType(eventType: string) {
  return eventType.replace(/_/g, " ");
}

type PromptTextareaProps = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "rows"> & {
  maxHeight?: number;
};

function PromptTextarea({ className, maxHeight = 240, onInput, ...props }: PromptTextareaProps) {
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);

  function syncHeight() {
    const textarea = textareaRef.current;
    if (!textarea) {
      return;
    }

    textarea.style.height = "0px";
    const nextHeight = Math.min(textarea.scrollHeight, maxHeight);
    textarea.style.height = `${nextHeight}px`;
    textarea.style.overflowY = textarea.scrollHeight > maxHeight ? "auto" : "hidden";
  }

  useLayoutEffect(() => {
    syncHeight();
  }, [maxHeight, props.value]);

  return (
    <textarea
      {...props}
      ref={textareaRef}
      rows={1}
      className={className}
      onInput={(event) => {
        syncHeight();
        onInput?.(event);
      }}
    />
  );
}

export default function WhatsAppPage() {
  const [status, setStatus] = useState<WhatsAppStatus | null>(null);
  const [bookingSettings, setBookingSettings] = useState<VenueBookingSettings | null>(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [turnDurationMinutes, setTurnDurationMinutes] = useState("120");
  const [whatsappAssistantPrompt, setWhatsappAssistantPrompt] = useState("");
  const [whatsappBusinessAccountId, setWhatsappBusinessAccountId] = useState("");
  const [whatsappBusinessId, setWhatsappBusinessId] = useState("");
  const [whatsappPhoneNumberId, setWhatsappPhoneNumberId] = useState("");
  const [whatsappDisplayPhoneNumber, setWhatsappDisplayPhoneNumber] = useState("");
  const [whatsappVerifiedName, setWhatsappVerifiedName] = useState("");
  const [whatsappAccessToken, setWhatsappAccessToken] = useState("");
  const [resetWhatsappAccessToken, setResetWhatsappAccessToken] = useState(false);
  const [logs, setLogs] = useState<WhatsAppEventLog[]>([]);
  const [to, setTo] = useState("");
  const [message, setMessage] = useState(defaultMessage);
  const [loading, setLoading] = useState(true);
  const [validating, setValidating] = useState(false);
  const [sending, setSending] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [feedback, setFeedback] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function loadPage() {
    setLoading(true);
    setError(null);
    try {
      const [statusResponse, logsResponse, settingsResponse] = await Promise.all([
        apiFetch<WhatsAppStatus>("/whatsapp/status"),
        apiFetch<WhatsAppEventLog[]>("/whatsapp/logs?limit=20"),
        apiFetch<VenueBookingSettings>("/booking-settings")
      ]);
      setStatus(statusResponse);
      setLogs(logsResponse);
      setBookingSettings(settingsResponse);
      setTurnDurationMinutes(String(settingsResponse.turn_duration_minutes));
      setWhatsappAssistantPrompt(settingsResponse.whatsapp_assistant_prompt || "");
      setWhatsappBusinessAccountId(settingsResponse.whatsapp_business_account_id || "");
      setWhatsappBusinessId(settingsResponse.whatsapp_business_id || "");
      setWhatsappPhoneNumberId(settingsResponse.whatsapp_phone_number_id || "");
      setWhatsappDisplayPhoneNumber(settingsResponse.whatsapp_display_phone_number || "");
      setWhatsappVerifiedName(settingsResponse.whatsapp_verified_name || "");
      setWhatsappAccessToken("");
      setResetWhatsappAccessToken(false);
      setMessage(
        `Ciao, ti confermiamo la tua prenotazione da ${settingsResponse.venue_name}. Se hai bisogno di modifiche, rispondi pure a questo messaggio.`
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Impossibile caricare il pannello WhatsApp");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadPage();
  }, []);

  async function handleValidateConfig() {
    setValidating(true);
    setFeedback(null);
    setError(null);
    try {
      const response = await apiFetch<WhatsAppConfigValidation>("/whatsapp/validate-config", { method: "POST" });
      const bits = [response.detail];
      if (response.verified_name) {
        bits.push(`Profilo verificato: ${response.verified_name}`);
      }
      setFeedback(bits.join(" "));
      await loadPage();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Controllo del canale non riuscito");
    } finally {
      setValidating(false);
    }
  }

  async function handleSendMessage(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSending(true);
    setFeedback(null);
    setError(null);
    try {
      const response = await apiFetch<WhatsAppSendTestResponse>("/whatsapp/test-message", {
        method: "POST",
        body: JSON.stringify({ to, message })
      });
      setFeedback(response.detail);
      setTo("");
      await loadPage();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Invio messaggio non riuscito");
    } finally {
      setSending(false);
    }
  }

  async function handleSaveBookingAutomationSettings(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!bookingSettings) {
      return;
    }

    setSavingSettings(true);
    setFeedback(null);
    setError(null);
    try {
      const response = await apiFetch<VenueBookingSettings>(`/booking-settings/${bookingSettings.venue_id}`, {
        method: "PUT",
        body: JSON.stringify({
          turn_duration_minutes: Number(turnDurationMinutes),
          whatsapp_assistant_prompt: whatsappAssistantPrompt,
          whatsapp_business_account_id: whatsappBusinessAccountId,
          whatsapp_business_id: whatsappBusinessId,
          whatsapp_phone_number_id: whatsappPhoneNumberId,
          whatsapp_display_phone_number: whatsappDisplayPhoneNumber,
          whatsapp_verified_name: whatsappVerifiedName,
          whatsapp_access_token: whatsappAccessToken || null,
          reset_whatsapp_access_token: resetWhatsappAccessToken
        })
      });
      setBookingSettings(response);
      setTurnDurationMinutes(String(response.turn_duration_minutes));
      setWhatsappAssistantPrompt(response.whatsapp_assistant_prompt || "");
      setWhatsappBusinessAccountId(response.whatsapp_business_account_id || "");
      setWhatsappBusinessId(response.whatsapp_business_id || "");
      setWhatsappPhoneNumberId(response.whatsapp_phone_number_id || "");
      setWhatsappDisplayPhoneNumber(response.whatsapp_display_phone_number || "");
      setWhatsappVerifiedName(response.whatsapp_verified_name || "");
      setWhatsappAccessToken("");
      setResetWhatsappAccessToken(false);
      setFeedback("Linea WhatsApp del locale aggiornata. Le credenziali restano isolate per questo account.");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Aggiornamento impostazioni WhatsApp non riuscito");
    } finally {
      setSavingSettings(false);
    }
  }

  return (
    <main className="space-y-6">
      <section className="panel-strong">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <p className="text-[11px] uppercase tracking-[0.32em] text-white/60">Canale conversazionale</p>
            <h2 className="mt-3 font-display text-4xl text-white">WhatsApp del locale</h2>
            <p className="mt-3 max-w-3xl text-sm leading-6 text-white/72">
              Conferme, promemoria e comunicazioni in un solo pannello, con uno stile piu pulito e una lettura piu
              immediata.
            </p>
          </div>
          <button className="button-ghost" onClick={() => void loadPage()} type="button">
            Aggiorna
          </button>
        </div>
      </section>

      <section className="grid gap-6 lg:grid-cols-[1.05fr,1fr]">
        <div className="space-y-6">
          <div className="panel">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="section-kicker">Stato canale</p>
                <h3 className="mt-3 font-display text-3xl text-ink">Linea WhatsApp</h3>
                <p className="mt-2 text-sm text-stone-600">
                  Controlla se il canale e pronto a inviare e ricevere messaggi dal locale.
                </p>
              </div>
              <span
                className={`subtle-pill ${status?.configured ? "bg-emerald-100 text-emerald-800" : "bg-amber-100 text-amber-800"}`}
              >
                {status?.configured ? "Pronta" : "Da completare"}
              </span>
            </div>

            {loading ? <p className="mt-4 text-sm text-stone-500">Caricamento stato...</p> : null}
            {status ? (
              <div className="mt-5 grid gap-3 sm:grid-cols-2">
                <div className="soft-card">
                  <p className="text-xs uppercase tracking-[0.18em] text-stone-500">Linea collegata</p>
                  <p className="mt-2 font-semibold text-stone-800">
                    {status.display_phone_number || status.phone_number_id_masked || "Non ancora collegata"}
                  </p>
                </div>
                <div className="soft-card">
                  <p className="text-xs uppercase tracking-[0.18em] text-stone-500">Nome verificato</p>
                  <p className="mt-2 font-semibold text-stone-800">
                    {status.verified_name || "Non disponibile"}
                  </p>
                </div>
                <div className="soft-card">
                  <p className="text-xs uppercase tracking-[0.18em] text-stone-500">Canale</p>
                  <p className="mt-2 font-semibold text-stone-800">
                    {status.configured ? "Disponibile per il team" : "In attesa di collegamento"}
                  </p>
                </div>
                <div className="soft-card">
                  <p className="text-xs uppercase tracking-[0.18em] text-stone-500">Credenziali</p>
                  <p className="mt-2 font-semibold text-stone-800">
                    {status.configured ? "Canale attivo" : "Da completare"}
                  </p>
                </div>
              </div>
            ) : null}

            {status ? (
              <div className="mt-5 rounded-[24px] bg-stone-100 p-4 text-sm text-stone-700">
                <p className="font-semibold text-stone-800">Stato del collegamento</p>
                <p className="mt-2">{status.message}</p>
                <p className="mt-3 text-xs uppercase tracking-[0.16em] text-stone-500">
                  Locale: {status.venue_name} · Phone Number ID: {status.phone_number_id || "non configurato"}
                </p>
              </div>
            ) : null}

            <div className="mt-5 flex flex-wrap gap-3">
              <button className="button-primary" disabled={validating || loading} onClick={() => void handleValidateConfig()} type="button">
                {validating ? "Controllo in corso..." : "Controlla collegamento"}
              </button>
            </div>
          </div>

          <div className="panel">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p className="section-kicker">Automazione prenotazioni</p>
                <h3 className="mt-3 font-display text-3xl text-ink">Numero WhatsApp e prompt</h3>
                <p className="mt-2 text-sm text-stone-600">
                  Qui il locale deve inserire solo i dati della linea WhatsApp che gli sono stati forniti.
                </p>
              </div>
              <button
                aria-expanded={settingsOpen}
                className="button-ghost min-w-44"
                onClick={() => setSettingsOpen((current) => !current)}
                type="button"
              >
                {settingsOpen ? "Chiudi impostazioni" : "Impostazioni"}
              </button>
            </div>

            <div className={`settings-drawer ${settingsOpen ? "is-open" : ""}`}>
              <div className="settings-drawer-inner">
                <form className="mt-5 space-y-4" onSubmit={(event) => void handleSaveBookingAutomationSettings(event)}>
                  <label className="block">
                    <span className="mb-2 block text-sm text-stone-600">Durata turno in minuti</span>
                    <input
                      className="field"
                      type="number"
                      min="30"
                      step="15"
                      value={turnDurationMinutes}
                      onChange={(event) => setTurnDurationMinutes(event.target.value)}
                      required
                    />
                  </label>

                  <div className="rounded-[24px] bg-stone-100 p-4 text-sm text-stone-700">
                    <p className="font-semibold text-stone-800">Dati da inserire</p>
                    <p className="mt-2">
                      Inserisci solo il <strong>Phone Number ID</strong> e, se richiesto, il <strong>token</strong> della
                      linea che ti è stata fornita.
                    </p>
                  </div>

                  <div className="grid gap-4 md:grid-cols-2">
                    <label className="block">
                      <span className="mb-2 block text-sm text-stone-600">Phone Number ID</span>
                      <input
                        className="field"
                        value={whatsappPhoneNumberId}
                        onChange={(event) => setWhatsappPhoneNumberId(event.target.value)}
                        placeholder="Phone number id della linea"
                      />
                    </label>
                    <label className="block">
                      <span className="mb-2 block text-sm text-stone-600">Numero visualizzato</span>
                      <input
                        className="field"
                        value={whatsappDisplayPhoneNumber}
                        onChange={(event) => setWhatsappDisplayPhoneNumber(event.target.value)}
                        placeholder="+39..."
                      />
                    </label>
                    <label className="block">
                      <span className="mb-2 block text-sm text-stone-600">Nome verificato</span>
                      <input
                        className="field"
                        value={whatsappVerifiedName}
                        onChange={(event) => setWhatsappVerifiedName(event.target.value)}
                        placeholder="Nome verificato su Meta"
                      />
                    </label>
                    <label className="block">
                      <span className="mb-2 block text-sm text-stone-600">Nuovo access token</span>
                      <input
                        className="field"
                        type="password"
                        value={whatsappAccessToken}
                        onChange={(event) => {
                          setWhatsappAccessToken(event.target.value);
                          if (event.target.value) {
                            setResetWhatsappAccessToken(false);
                          }
                        }}
                        placeholder={bookingSettings?.whatsapp_access_token_configured ? "Token gia configurato" : "Incolla qui il token"}
                      />
                    </label>
                  </div>

                  <label className="flex items-center gap-3 rounded-[20px] border border-stone-200 bg-white/80 px-4 py-3">
                    <input
                      type="checkbox"
                      checked={resetWhatsappAccessToken}
                      onChange={(event) => {
                        setResetWhatsappAccessToken(event.target.checked);
                        if (event.target.checked) {
                          setWhatsappAccessToken("");
                        }
                      }}
                    />
                    <span className="text-sm text-stone-700">
                      Rimuovi il token salvato per questo locale
                      {bookingSettings?.whatsapp_access_token_configured ? " (attualmente presente)" : ""}
                    </span>
                  </label>

                  <label className="block">
                    <span className="mb-2 block text-sm text-stone-600">Prompt aggiuntivo per WhatsApp prenotazioni</span>
                    <PromptTextarea
                      className="field min-h-[52px] resize-none overflow-y-hidden"
                      value={whatsappAssistantPrompt}
                      onChange={(event) => setWhatsappAssistantPrompt(event.target.value)}
                    />
                  </label>

                  {bookingSettings ? (
                    <div className="space-y-4">
                      <div className="rounded-[24px] bg-stone-100 p-4 text-sm text-stone-700">
                        <p className="font-semibold text-stone-800">Linea del locale</p>
                        <p className="mt-2">{bookingSettings.venue_name}</p>
                        <p className="mt-2 text-sm text-stone-600">
                          {bookingSettings.whatsapp_display_phone_number || "Numero visualizzato non ancora rilevato"}
                        </p>
                        <p className="mt-2 text-xs uppercase tracking-[0.16em] text-stone-500">
                          {bookingSettings.whatsapp_verified_name
                            ? `Nome verificato: ${bookingSettings.whatsapp_verified_name}`
                            : "Nome verificato non ancora disponibile"}
                        </p>
                      </div>

                      <div className="rounded-[24px] bg-stone-100 p-4 text-sm text-stone-700">
                        <p className="font-semibold text-stone-800">Prompt base condiviso</p>
                        <pre className="mt-3 whitespace-pre-wrap font-sans text-sm leading-6 text-stone-700">
                          {bookingSettings.whatsapp_assistant_base_prompt}
                        </pre>
                      </div>

                      <div className="rounded-[24px] bg-stone-100 p-4 text-sm text-stone-700">
                        <p className="font-semibold text-stone-800">Prompt effettivo del canale</p>
                        <pre className="mt-3 whitespace-pre-wrap font-sans text-sm leading-6 text-stone-700">
                          {bookingSettings.whatsapp_assistant_effective_prompt}
                        </pre>
                      </div>
                    </div>
                  ) : null}

                  <div className="flex justify-end">
                    <button className="button-primary min-w-52" disabled={savingSettings || loading} type="submit">
                      {savingSettings ? "Salvataggio..." : "Salva impostazioni WhatsApp"}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div className="panel">
            <p className="section-kicker">Invio rapido</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Invia anteprima</h3>
            <p className="mt-2 text-sm text-stone-600">
              Invia un messaggio di prova per verificare tono, chiarezza e recapito prima di usarlo con gli ospiti.
            </p>

            <form className="mt-5 space-y-4" onSubmit={(event) => void handleSendMessage(event)}>
              <label className="block">
                <span className="mb-2 block text-sm text-stone-600">Numero destinatario</span>
                <input
                  className="field"
                  placeholder="+393331234567"
                  required
                  value={to}
                  onChange={(event) => setTo(event.target.value)}
                />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm text-stone-600">Messaggio</span>
                <textarea
                  className="field min-h-32"
                  required
                  value={message}
                  onChange={(event) => setMessage(event.target.value)}
                />
              </label>
              <div className="flex justify-end">
                <button className="button-primary min-w-52" disabled={sending || loading} type="submit">
                  {sending ? "Invio in corso..." : "Invia anteprima"}
                </button>
              </div>
            </form>
          </div>

          <div className="panel">
            <p className="section-kicker">Buone pratiche</p>
            <h3 className="mt-3 font-display text-3xl text-ink">Messaggi piu efficaci</h3>
            <div className="mt-4 space-y-3 text-sm text-stone-600">
              <p>1. Mantieni i messaggi brevi, chiari e facili da leggere da mobile.</p>
              <p>2. Conferma sempre data, ora e numero ospiti quando scrivi al cliente.</p>
              <p>3. Chiudi con un invito semplice a rispondere in caso di modifiche o richieste.</p>
              <p>4. Usa questa sezione per verificare il tono prima di inviare comunicazioni ricorrenti.</p>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="flex items-center justify-between gap-4">
            <div>
              <p className="section-kicker">Storico</p>
              <h3 className="mt-3 font-display text-3xl text-ink">Ultimi aggiornamenti</h3>
              <p className="mt-2 text-sm text-stone-600">
                Qui trovi gli ultimi invii e gli aggiornamenti recenti del canale, senza dettagli tecnici superflui.
              </p>
            </div>
            <span className="subtle-pill bg-stone-100 text-stone-700">{logs.length} eventi</span>
          </div>

          {feedback ? <p className="notice is-success mt-4">{feedback}</p> : null}
          {error ? <p className="notice is-error mt-4">{error}</p> : null}

          <div className="mt-5 space-y-4">
            {logs.map((log) => (
              <div key={log.id} className="soft-card">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <p className="text-xs uppercase tracking-[0.18em] text-stone-500">{formatEventType(log.event_type)}</p>
                    <p className="mt-1 font-semibold text-stone-800">{log.summary}</p>
                  </div>
                  <p className="text-xs text-stone-500">{new Date(log.created_at).toLocaleString("it-IT")}</p>
                </div>
                <div className="mt-3 flex flex-wrap gap-4 text-sm text-stone-600">
                  <p>Telefono: {log.contact_phone || "n/d"}</p>
                </div>
              </div>
            ))}

            {!loading && logs.length === 0 ? (
              <p className="rounded-2xl bg-stone-100 p-4 text-sm text-stone-600">
                Nessun aggiornamento ancora registrato. Appena invii o ricevi messaggi, li vedrai qui.
              </p>
            ) : null}
          </div>
        </div>
      </section>
    </main>
  );
}
