'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Swal from 'sweetalert2';
import { RequireRole } from '@/lib/auth-context';
import { listPages, updatePage } from '@/lib/services/pages';
import { publicHrefForSlug } from '@/lib/pages-content';
import {
  SERVICE_ICON_OPTIONS,
  type PageServiceItem,
  type SitePage,
} from '@/lib/types';
import { BackLink, ErrorAlert, Loading, PageHeader } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

export default function EditarPaginaPage() {
  const params = useParams<{ slug: string }>();
  const slug = typeof params?.slug === 'string' ? params.slug : '';

  return (
    <RequireRole roles={['admin']}>
      <PageEditor slug={slug} />
    </RequireRole>
  );
}

interface FormState {
  title: string;
  subtitle: string;
  metaTitle: string;
  metaDescription: string;
  isPublished: boolean;
  heroTitle: string;
  heroSubtitle: string;
  ctaTitle: string;
  ctaText: string;
  ctaButtonLabel: string;
  ctaButtonHref: string;
  services: PageServiceItem[];
}

function toFormState(page: SitePage): FormState {
  return {
    title: page.title ?? '',
    subtitle: page.subtitle ?? '',
    metaTitle: page.metaTitle ?? '',
    metaDescription: page.metaDescription ?? '',
    isPublished: page.isPublished,
    heroTitle: page.content?.hero?.title ?? '',
    heroSubtitle: page.content?.hero?.subtitle ?? '',
    ctaTitle: page.content?.cta?.title ?? '',
    ctaText: page.content?.cta?.text ?? '',
    ctaButtonLabel: page.content?.cta?.buttonLabel ?? '',
    ctaButtonHref: page.content?.cta?.buttonHref ?? '',
    services: Array.isArray(page.content?.services)
      ? page.content.services.map((item) => ({
          icon: item.icon ?? '',
          title: item.title ?? '',
          description: item.description ?? '',
        }))
      : [],
  };
}

function PageEditor({ slug }: { slug: string }) {
  const [form, setForm] = useState<FormState | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const pages = await listPages();
      const page = pages.find((p) => p.slug === slug);
      setForm(page ? toFormState(page) : null);
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [slug]);

  useEffect(() => {
    load();
  }, [load]);

  function patch(values: Partial<FormState>) {
    setForm((current) => (current ? { ...current, ...values } : current));
  }

  function updateService(index: number, values: Partial<PageServiceItem>) {
    setForm((current) => {
      if (!current) return current;
      const services = current.services.map((item, i) =>
        i === index ? { ...item, ...values } : item,
      );
      return { ...current, services };
    });
  }

  function addService() {
    setForm((current) =>
      current
        ? {
            ...current,
            services: [
              ...current.services,
              { icon: 'bi-check-circle', title: '', description: '' },
            ],
          }
        : current,
    );
  }

  function removeService(index: number) {
    setForm((current) =>
      current
        ? {
            ...current,
            services: current.services.filter((_, i) => i !== index),
          }
        : current,
    );
  }

  function moveService(index: number, direction: -1 | 1) {
    setForm((current) => {
      if (!current) return current;
      const target = index + direction;
      if (target < 0 || target >= current.services.length) return current;
      const services = [...current.services];
      [services[index], services[target]] = [services[target], services[index]];
      return { ...current, services };
    });
  }

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!form) return;

    const invalid = form.services.find((s) => !s.title.trim());
    if (invalid) {
      Swal.fire({
        icon: 'warning',
        title: 'Serviço sem título',
        text: 'Preencha o título de todos os serviços.',
      });
      return;
    }

    setSaving(true);
    try {
      await updatePage(slug, {
        title: form.title.trim(),
        subtitle: form.subtitle.trim() || null,
        metaTitle: form.metaTitle.trim() || null,
        metaDescription: form.metaDescription.trim() || null,
        isPublished: form.isPublished,
        content: {
          hero: {
            title: form.heroTitle.trim(),
            subtitle: form.heroSubtitle.trim(),
          },
          services: form.services.map((s) => ({
            icon: s.icon.trim() || 'bi-check-circle',
            title: s.title.trim(),
            description: s.description?.trim() || null,
          })),
          cta: {
            title: form.ctaTitle.trim(),
            text: form.ctaText.trim(),
            buttonLabel: form.ctaButtonLabel.trim(),
            buttonHref: form.ctaButtonHref.trim(),
          },
        },
      });
      await Swal.fire({
        icon: 'success',
        title: 'Página salva!',
        timer: 1200,
        showConfirmButton: false,
      });
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <BackLink href="/painel/paginas" label="Páginas do site" />

      {error && <ErrorAlert message={error} onRetry={load} />}

      {loading ? (
        <Loading label="Carregando página…" />
      ) : !form ? (
        <div className="alert alert-warning" role="alert">
          Página <code>{slug}</code> não encontrada.
        </div>
      ) : (
        <form onSubmit={handleSubmit}>
          <PageHeader
            title={`Editar: ${form.title || slug}`}
            subtitle={`Slug: ${slug}`}
            action={
              <div className="d-flex gap-2">
                <Link
                  href={publicHrefForSlug(slug)}
                  target="_blank"
                  className="btn btn-outline-secondary"
                >
                  <i className="bi bi-box-arrow-up-right me-1" />
                  Ver no site
                </Link>
                <button type="submit" className="btn btn-primary" disabled={saving}>
                  {saving ? (
                    <span className="spinner-border spinner-border-sm me-1" />
                  ) : (
                    <i className="bi bi-check-lg me-1" />
                  )}
                  Salvar
                </button>
              </div>
            }
          />

          <div className="row g-4">
            <div className="col-lg-8">
              <div className="card border-0 shadow-sm mb-4">
                <div className="card-body">
                  <h2 className="h5 mb-3">Cabeçalho (hero)</h2>
                  <div className="mb-3">
                    <label className="form-label" htmlFor="hero-title">
                      Título
                    </label>
                    <input
                      id="hero-title"
                      className="form-control"
                      value={form.heroTitle}
                      maxLength={120}
                      onChange={(e) => patch({ heroTitle: e.target.value })}
                    />
                  </div>
                  <div className="mb-0">
                    <label className="form-label" htmlFor="hero-subtitle">
                      Subtítulo
                    </label>
                    <textarea
                      id="hero-subtitle"
                      className="form-control"
                      rows={2}
                      value={form.heroSubtitle}
                      onChange={(e) => patch({ heroSubtitle: e.target.value })}
                    />
                  </div>
                </div>
              </div>

              <div className="card border-0 shadow-sm mb-4">
                <div className="card-body">
                  <div className="d-flex justify-content-between align-items-center mb-3">
                    <h2 className="h5 mb-0">Serviços</h2>
                    <button
                      type="button"
                      className="btn btn-sm btn-outline-primary"
                      onClick={addService}
                    >
                      <i className="bi bi-plus-lg me-1" />
                      Adicionar serviço
                    </button>
                  </div>

                  <datalist id="service-icons">
                    {SERVICE_ICON_OPTIONS.map((icon) => (
                      <option key={icon} value={icon} />
                    ))}
                  </datalist>

                  {form.services.length === 0 && (
                    <p className="text-muted mb-0">
                      Nenhum serviço cadastrado. Adicione o primeiro item.
                    </p>
                  )}

                  {form.services.map((service, index) => (
                    <div
                      className="border rounded p-3 mb-3 bg-body-tertiary"
                      key={index}
                    >
                      <div className="d-flex justify-content-between align-items-center mb-2">
                        <span className="fw-semibold text-muted small">
                          Serviço {index + 1}
                        </span>
                        <div className="btn-group btn-group-sm">
                          <button
                            type="button"
                            className="btn btn-outline-secondary"
                            onClick={() => moveService(index, -1)}
                            disabled={index === 0}
                            aria-label="Mover para cima"
                          >
                            <i className="bi bi-arrow-up" />
                          </button>
                          <button
                            type="button"
                            className="btn btn-outline-secondary"
                            onClick={() => moveService(index, 1)}
                            disabled={index === form.services.length - 1}
                            aria-label="Mover para baixo"
                          >
                            <i className="bi bi-arrow-down" />
                          </button>
                          <button
                            type="button"
                            className="btn btn-outline-danger"
                            onClick={() => removeService(index)}
                            aria-label="Remover serviço"
                          >
                            <i className="bi bi-trash" />
                          </button>
                        </div>
                      </div>

                      <div className="row g-2">
                        <div className="col-md-4">
                          <label className="form-label small" htmlFor={`icon-${index}`}>
                            Ícone (ex.: bi-gem)
                          </label>
                          <div className="input-group input-group-sm">
                            <span className="input-group-text">
                              <i
                                className={`bi ${
                                  service.icon || 'bi-check-circle'
                                }`}
                              />
                            </span>
                            <input
                              id={`icon-${index}`}
                              className="form-control"
                              list="service-icons"
                              value={service.icon}
                              placeholder="bi-gem"
                              onChange={(e) =>
                                updateService(index, { icon: e.target.value })
                              }
                            />
                          </div>
                        </div>
                        <div className="col-md-8">
                          <label className="form-label small" htmlFor={`title-${index}`}>
                            Título
                          </label>
                          <input
                            id={`title-${index}`}
                            className="form-control form-control-sm"
                            value={service.title}
                            maxLength={120}
                            onChange={(e) =>
                              updateService(index, { title: e.target.value })
                            }
                          />
                        </div>
                        <div className="col-12">
                          <label
                            className="form-label small"
                            htmlFor={`desc-${index}`}
                          >
                            Descrição
                          </label>
                          <textarea
                            id={`desc-${index}`}
                            className="form-control form-control-sm"
                            rows={2}
                            value={service.description ?? ''}
                            onChange={(e) =>
                              updateService(index, {
                                description: e.target.value,
                              })
                            }
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="card border-0 shadow-sm mb-4">
                <div className="card-body">
                  <h2 className="h5 mb-3">Chamada final (CTA)</h2>
                  <div className="row g-3">
                    <div className="col-md-6">
                      <label className="form-label" htmlFor="cta-title">
                        Título
                      </label>
                      <input
                        id="cta-title"
                        className="form-control"
                        value={form.ctaTitle}
                        onChange={(e) => patch({ ctaTitle: e.target.value })}
                      />
                    </div>
                    <div className="col-md-6">
                      <label className="form-label" htmlFor="cta-text">
                        Texto
                      </label>
                      <input
                        id="cta-text"
                        className="form-control"
                        value={form.ctaText}
                        onChange={(e) => patch({ ctaText: e.target.value })}
                      />
                    </div>
                    <div className="col-md-6">
                      <label className="form-label" htmlFor="cta-button-label">
                        Texto do botão
                      </label>
                      <input
                        id="cta-button-label"
                        className="form-control"
                        value={form.ctaButtonLabel}
                        onChange={(e) =>
                          patch({ ctaButtonLabel: e.target.value })
                        }
                      />
                    </div>
                    <div className="col-md-6">
                      <label className="form-label" htmlFor="cta-button-href">
                        Link do botão
                      </label>
                      <input
                        id="cta-button-href"
                        className="form-control"
                        value={form.ctaButtonHref}
                        onChange={(e) => patch({ ctaButtonHref: e.target.value })}
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-lg-4">
              <div className="card border-0 shadow-sm mb-4">
                <div className="card-body">
                  <h2 className="h5 mb-3">Publicação</h2>
                  <div className="form-check form-switch mb-3">
                    <input
                      id="is-published"
                      className="form-check-input"
                      type="checkbox"
                      role="switch"
                      checked={form.isPublished}
                      onChange={(e) => patch({ isPublished: e.target.checked })}
                    />
                    <label className="form-check-label" htmlFor="is-published">
                      Publicada no site
                    </label>
                  </div>
                  <p className="text-muted small mb-0">
                    Quando despublicada, a página retorna 404 para visitantes até
                    ser publicada novamente.
                  </p>
                </div>
              </div>

              <div className="card border-0 shadow-sm">
                <div className="card-body">
                  <h2 className="h5 mb-3">SEO</h2>
                  <div className="mb-3">
                    <label className="form-label" htmlFor="page-title">
                      Título da página
                    </label>
                    <input
                      id="page-title"
                      className="form-control"
                      value={form.title}
                      maxLength={180}
                      onChange={(e) => patch({ title: e.target.value })}
                    />
                  </div>
                  <div className="mb-3">
                    <label className="form-label" htmlFor="page-subtitle">
                      Subtítulo
                    </label>
                    <input
                      id="page-subtitle"
                      className="form-control"
                      value={form.subtitle}
                      maxLength={255}
                      onChange={(e) => patch({ subtitle: e.target.value })}
                    />
                  </div>
                  <div className="mb-3">
                    <label className="form-label" htmlFor="meta-title">
                      Meta title
                    </label>
                    <input
                      id="meta-title"
                      className="form-control"
                      value={form.metaTitle}
                      maxLength={180}
                      onChange={(e) => patch({ metaTitle: e.target.value })}
                    />
                  </div>
                  <div className="mb-0">
                    <label className="form-label" htmlFor="meta-description">
                      Meta description
                    </label>
                    <textarea
                      id="meta-description"
                      className="form-control"
                      rows={3}
                      value={form.metaDescription}
                      maxLength={320}
                      onChange={(e) =>
                        patch({ metaDescription: e.target.value })
                      }
                    />
                  </div>
                </div>
              </div>

              <button
                type="submit"
                className="btn btn-primary w-100 mt-4"
                disabled={saving}
              >
                {saving ? (
                  <span className="spinner-border spinner-border-sm me-1" />
                ) : (
                  <i className="bi bi-check-lg me-1" />
                )}
                Salvar
              </button>
            </div>
          </div>
        </form>
      )}
    </>
  );
}
