import { FormEvent, useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";

import { portalRuntimeConfig } from "../config/runtime";
import {
  GoogleWorkspaceCreateResponse,
  GoogleWorkspaceDocumentPreview,
  GoogleWorkspaceStatusResponse,
  createGoogleWorkspaceDocument,
  disconnectGoogleWorkspace,
  fetchGoogleWorkspaceStatus,
  generateGoogleWorkspacePreview,
  startGoogleWorkspaceAuthorization
} from "../lib/api";
import { PromptTextarea } from "../components/PromptTextarea";

type DocumentKind = "doc" | "sheet";

function buildFlashMessage(searchParams: URLSearchParams): string | null {
  const google = searchParams.get("google");
  const detail = searchParams.get("detail");

  if (google === "connected") {
    return "Account Google collegato. Ora puoi creare e salvare i tuoi documenti.";
  }

  if (google === "error") {
    return detail ? `Autorizzazione Google non completata: ${detail}` : "Autorizzazione Google non completata.";
  }

  return null;
}

function buildGeneratedTitle(kind: DocumentKind, prompt: string): string {
  const fallback = kind === "doc" ? "Documento operativo" : "Foglio operativo";
  const cleanedPrompt = prompt
    .replace(/\s+/g, " ")
    .replace(/[^a-zA-Z0-9À-ÖØ-öø-ÿ\s-]/g, "")
    .trim();

  if (!cleanedPrompt) {
    return fallback;
  }

  const compactTitle = cleanedPrompt.split(" ").filter(Boolean).slice(0, 6).join(" ").slice(0, 80).trim();
  if (compactTitle.length < 3) {
    return fallback;
  }

  return compactTitle.charAt(0).toUpperCase() + compactTitle.slice(1);
}

export function CloudDocumentsPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [status, setStatus] = useState<GoogleWorkspaceStatusResponse | null>(null);
  const [statusError, setStatusError] = useState<string | null>(null);
  const [statusBusy, setStatusBusy] = useState(false);
  const [actionBusy, setActionBusy] = useState<"connect" | "disconnect" | null>(null);
  const [previewBusy, setPreviewBusy] = useState(false);
  const [createBusy, setCreateBusy] = useState(false);
  const [kind, setKind] = useState<DocumentKind>("doc");
  const [titleOverride, setTitleOverride] = useState("");
  const [prompt, setPrompt] = useState("");
  const [destinationFolderId, setDestinationFolderId] = useState("");
  const [preview, setPreview] = useState<GoogleWorkspaceDocumentPreview | null>(null);
  const [previewError, setPreviewError] = useState<string | null>(null);
  const [created, setCreated] = useState<GoogleWorkspaceCreateResponse | null>(null);
  const [createError, setCreateError] = useState<string | null>(null);
  const [flashMessage, setFlashMessage] = useState<string | null>(null);

  useEffect(() => {
    async function loadStatus() {
      setStatusBusy(true);
      try {
        const response = await fetchGoogleWorkspaceStatus(portalRuntimeConfig.apiHubBaseUrl);
        setStatus(response);
        setStatusError(null);
      } catch (error) {
        const message = error instanceof Error ? error.message : "Stato Google Workspace non disponibile";
        setStatusError(message);
      } finally {
        setStatusBusy(false);
      }
    }

    void loadStatus();
  }, []);

  useEffect(() => {
    const message = buildFlashMessage(searchParams);
    if (!message) {
      return;
    }

    setFlashMessage(message);
    setSearchParams({}, { replace: true });
  }, [searchParams, setSearchParams]);

  async function refreshStatus() {
    setStatusBusy(true);
    try {
      const response = await fetchGoogleWorkspaceStatus(portalRuntimeConfig.apiHubBaseUrl);
      setStatus(response);
      setStatusError(null);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Stato Google Workspace non disponibile";
      setStatusError(message);
    } finally {
      setStatusBusy(false);
    }
  }

  async function handleConnectGoogle() {
    setActionBusy("connect");
    setStatusError(null);

    try {
      const response = await startGoogleWorkspaceAuthorization(portalRuntimeConfig.apiHubBaseUrl, "/documents");
      window.location.assign(response.authorization_url);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Avvio autorizzazione Google fallito";
      setStatusError(message);
      setActionBusy(null);
    }
  }

  async function handleDisconnectGoogle() {
    setActionBusy("disconnect");
    setCreateError(null);

    try {
      await disconnectGoogleWorkspace(portalRuntimeConfig.apiHubBaseUrl);
      setFlashMessage("Account Google scollegato.");
      setCreated(null);
      await refreshStatus();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Disconnessione Google fallita";
      setStatusError(message);
    } finally {
      setActionBusy(null);
    }
  }

  async function handleGeneratePreview(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setPreviewBusy(true);
    setPreviewError(null);
    setCreateError(null);
    setCreated(null);

    try {
      const requestedTitle = titleOverride.trim() || buildGeneratedTitle(kind, prompt);
      const response = await generateGoogleWorkspacePreview(portalRuntimeConfig.apiHubBaseUrl, {
        kind,
        title: requestedTitle,
        prompt,
        destination_folder_id: destinationFolderId.trim() || undefined
      });
      setTitleOverride(response.title);
      setPreview(response);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Preview documento non disponibile";
      setPreviewError(message);
      setPreview(null);
    } finally {
      setPreviewBusy(false);
    }
  }

  async function handleCreateDocument() {
    if (!preview) {
      return;
    }

    setCreateBusy(true);
    setCreateError(null);

    try {
      const requestedTitle = titleOverride.trim() || preview.title;
      const response = await createGoogleWorkspaceDocument(portalRuntimeConfig.apiHubBaseUrl, {
        kind: preview.kind,
        title: requestedTitle,
        destination_folder_id: destinationFolderId.trim() || undefined,
        content: preview.content || undefined,
        columns: preview.columns,
        rows: preview.rows
      });
      setCreated(response);
      setFlashMessage("File creato su Google Workspace.");
      await refreshStatus();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Creazione documento Google fallita";
      setCreateError(message);
    } finally {
      setCreateBusy(false);
    }
  }

  function updateKind(nextKind: DocumentKind) {
    setKind(nextKind);
    setPreview(null);
    setCreated(null);
    setPreviewError(null);
    setCreateError(null);
    setTitleOverride("");
    setPrompt("");
  }

  const connectionLabel = statusBusy
    ? "Verifica collegamento in corso."
    : status?.next_step || "Configurazione Google non ancora disponibile.";

  return (
    <section className="documents-shell">
      <section className="panel documents-toolbar">
        <div className="documents-toolbar-copy">
          <p className="eyebrow">Documenti</p>
          <h2 className="page-title">Descrivi cosa ti serve, controlla l'anteprima e salva solo quando sei pronto.</h2>
          <p className="muted-copy">
            Crea materiali pronti da condividere con il team senza passare da schermate tecniche o procedure complesse.
          </p>
        </div>

        <div className="documents-toolbar-side">
          <div className="documents-account-bar">
            <div className="documents-account-chip">
              <span>Google</span>
              <strong>{status?.account_email || "Account non collegato"}</strong>
              <small>{connectionLabel}</small>
            </div>

            <div className="documents-account-actions">
              <button
                type="button"
                className="button-primary"
                onClick={() => void handleConnectGoogle()}
                disabled={actionBusy !== null || !status?.configured}
              >
                {actionBusy === "connect"
                  ? "Reindirizzamento..."
                  : status?.connected
                    ? status.ready
                      ? "Ricollega Google"
                      : "Concedi tutti i permessi"
                    : "Collega Google"}
              </button>
              <button
                type="button"
                className="button-secondary"
                onClick={() => void handleDisconnectGoogle()}
                disabled={actionBusy !== null || !status?.connected}
              >
                {actionBusy === "disconnect" ? "Scollegamento..." : "Scollega"}
              </button>
            </div>
          </div>
        </div>
      </section>

      {flashMessage ? (
        <section className={`status-banner${flashMessage.includes("non completata") ? " is-error" : " is-success"}`}>
          {flashMessage}
        </section>
      ) : null}

      {statusError ? <section className="status-banner is-error">{statusError}</section> : null}
      {status?.connected && !status.ready ? <section className="status-banner is-error">{status.next_step}</section> : null}

      <section className={`documents-workspace${preview ? " has-preview" : ""}`}>
        <section className="panel documents-composer">
          <div className="documents-composer-head">
            <div>
              <p className="eyebrow">Brief</p>
              <h3>Cosa vuoi creare?</h3>
            </div>
            <div className="documents-kind-switch" aria-label="Tipo documento">
              <button
                type="button"
                className={`kind-toggle${kind === "doc" ? " is-active" : ""}`}
                onClick={() => updateKind("doc")}
              >
                Google Doc
              </button>
              <button
                type="button"
                className={`kind-toggle${kind === "sheet" ? " is-active" : ""}`}
                onClick={() => updateKind("sheet")}
              >
                Google Sheet
              </button>
            </div>
          </div>

          <form className="documents-composer-form" onSubmit={handleGeneratePreview}>
            <label className="field documents-prompt-field">
              <span>Descrizione</span>
              <PromptTextarea
                value={prompt}
                onChange={(event) => {
                  setPrompt(event.target.value);
                  setTitleOverride("");
                  setPreview(null);
                  setCreated(null);
                  setPreviewError(null);
                  setCreateError(null);
                }}
              />
            </label>

            <div className="documents-submit-row">
              <button
                type="submit"
                className="button-primary"
                disabled={previewBusy || !prompt.trim()}
              >
                {previewBusy ? "Generazione anteprima..." : "Genera anteprima"}
              </button>
            </div>

            {previewError ? <p className="error-copy">{previewError}</p> : null}
          </form>
        </section>

        {preview ? (
          <section className="panel documents-preview-panel stack-md">
            <div className="documents-preview-head">
              <div>
                <p className="eyebrow">Preview</p>
                <h3>{titleOverride || preview.title}</h3>
              </div>
              <p className="muted-copy">{preview.summary}</p>
            </div>

            <div className="documents-preview-meta">
              <label className="field">
                <span>Nome file</span>
                <input
                  value={titleOverride}
                  onChange={(event) => {
                    setTitleOverride(event.target.value);
                    setCreated(null);
                    setCreateError(null);
                  }}
                />
              </label>

              <label className="field">
                <span>Nome cartella Drive</span>
                <input
                  value={destinationFolderId}
                  onChange={(event) => {
                    setDestinationFolderId(event.target.value);
                    setCreated(null);
                    setCreateError(null);
                  }}
                />
                <small className="field-helper">
                  Se la cartella non esiste ancora, la prepariamo automaticamente.
                </small>
              </label>
            </div>

            {preview.kind === "doc" ? (
              <article className="preview-doc">{preview.content}</article>
            ) : (
              <div className="preview-table-shell">
                <table className="preview-table">
                  <thead>
                    <tr>
                      {preview.columns.map((column) => (
                        <th key={column}>{column}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {preview.rows.map((row, rowIndex) => (
                      <tr key={`${preview.title}-${rowIndex}`}>
                        {row.map((cell, cellIndex) => (
                          <td key={`${preview.title}-${rowIndex}-${cellIndex}`}>{cell}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {createError ? <p className="error-copy">{createError}</p> : null}

            <div className="preview-actions">
              <button
                type="button"
                className="button-primary"
                onClick={() => void handleCreateDocument()}
                disabled={createBusy || !status?.connected || !status?.ready}
              >
                {createBusy ? "Salvataggio in corso..." : "Conferma e salva su Google"}
              </button>
              {!status?.connected ? (
                <p className="muted-copy">Collega l&apos;account Google per salvare il file.</p>
              ) : !status?.ready ? (
                <p className="muted-copy">Completa il collegamento Google prima di salvare il file.</p>
              ) : null}
            </div>

            {created ? (
              <div className="documents-created-card">
                <p className="eyebrow">Creato</p>
                <strong>{created.title}</strong>
                <p className="muted-copy">
                  File salvato sull&apos;account {created.account_email || "Google collegato"}.
                </p>
                <a className="button-secondary" href={created.web_url} target="_blank" rel="noreferrer">
                  Apri su Google
                </a>
              </div>
            ) : null}
          </section>
        ) : null}
      </section>
    </section>
  );
}
