'use client';

import { useState } from 'react';
import type { StoreSitePage } from '@alqove/api-client';
import { BLOCK_TYPES, BlockList, newBlock } from './block-editor';
import type { PageDraft } from './page-draft';
import { firstError, useSiteMutations } from './use-store-site';
import { ErrorText, Field, inputCls, Panel, PrimaryButton, SecondaryButton, Toggle } from './ui';

interface PagesPanelProps {
  storeId: string;
  pages: StoreSitePage[];
  selected: StoreSitePage | null;
  /** Draft lives in the parent so the preview pane sees unsaved edits too. */
  draft: PageDraft | null;
  onDraftChange: (patch: Partial<PageDraft>) => void;
  onSelectPage: (pageId: string) => void;
}

export function PagesPanel({
  storeId,
  pages,
  selected,
  draft,
  onDraftChange,
  onSelectPage,
}: PagesPanelProps) {
  const { createPage, updatePage, deletePage, reorderPages } = useSiteMutations(storeId);
  const [savedAt, setSavedAt] = useState<string | null>(null);

  function save() {
    if (!draft || !selected?.id) return;

    updatePage.mutate(
      {
        pageId: selected.id,
        payload: {
          title: draft.title,
          slug: draft.slug,
          nav_label: draft.navLabel || null,
          show_in_nav: draft.showInNav,
          // The API rejects unpublishing the landing page, so don't send it.
          ...(selected.is_home ? {} : { is_published: draft.isPublished }),
          blocks: draft.blocks,
          seo_title: draft.seoTitle || null,
          seo_description: draft.seoDescription || null,
        },
      },
      { onSuccess: () => setSavedAt(new Date().toLocaleTimeString()) },
    );
  }

  function addPage() {
    const title = prompt('Page name (e.g. "Our Story")')?.trim();
    if (!title) return;

    createPage.mutate(
      { title, slug: title, show_in_nav: true, is_published: true, blocks: [] },
      { onSuccess: (res) => res.data?.id && onSelectPage(res.data.id) },
    );
  }

  function movePage(index: number, delta: number) {
    const target = index + delta;
    if (target < 0 || target >= pages.length) return;

    const ids = pages.map((p) => p.id).filter((id): id is string => Boolean(id));
    [ids[index], ids[target]] = [ids[target], ids[index]];
    reorderPages.mutate(ids);
  }

  const error =
    firstError(updatePage.error) ??
    firstError(createPage.error) ??
    firstError(deletePage.error) ??
    firstError(reorderPages.error);

  return (
    <div className="space-y-6">
      <Panel
        title="Pages"
        description="The order here is the order of your site navigation."
        actions={
          <SecondaryButton onClick={addPage} disabled={createPage.isPending || pages.length >= 20}>
            + Add page
          </SecondaryButton>
        }
      >
        <ul className="divide-y divide-forest/10">
          {pages.map((page, index) => {
            const active = page.id === selected?.id;
            return (
              <li key={page.id} className="flex items-center gap-2 py-2">
                <button
                  type="button"
                  onClick={() => page.id && onSelectPage(page.id)}
                  className={`flex-1 text-left text-sm ${active ? 'font-semibold text-forest' : 'text-ink'}`}
                >
                  {page.title}
                  {page.is_home && (
                    <span className="ml-2 rounded bg-bone px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-ink/60">
                      Landing
                    </span>
                  )}
                  {!page.is_published && (
                    <span className="ml-2 rounded bg-terracotta/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-terracotta">
                      Draft
                    </span>
                  )}
                  <span className="ml-2 text-xs text-ink/40">/{page.slug}</span>
                </button>
                <SecondaryButton
                  onClick={() => movePage(index, -1)}
                  disabled={index === 0 || reorderPages.isPending}
                  ariaLabel={`Move ${page.title} up`}
                >
                  ↑
                </SecondaryButton>
                <SecondaryButton
                  onClick={() => movePage(index, 1)}
                  disabled={index === pages.length - 1 || reorderPages.isPending}
                  ariaLabel={`Move ${page.title} down`}
                >
                  ↓
                </SecondaryButton>
                {!page.is_home && (
                  <button
                    type="button"
                    onClick={() => {
                      if (page.id && confirm(`Delete the "${page.title}" page?`)) {
                        deletePage.mutate(page.id);
                      }
                    }}
                    className="rounded px-2 py-1.5 text-sm text-terracotta hover:underline"
                  >
                    Delete
                  </button>
                )}
              </li>
            );
          })}
        </ul>
        <ErrorText>{error}</ErrorText>
      </Panel>

      {draft && selected && (
        <Panel
          title={`Editing: ${draft.title || 'Untitled page'}`}
          description="Sections render top to bottom in the order below."
          actions={
            <div className="flex items-center gap-3">
              {savedAt && <span className="text-xs text-ink/60">Saved at {savedAt}</span>}
              <PrimaryButton onClick={save} disabled={updatePage.isPending}>
                {updatePage.isPending ? 'Saving…' : 'Save page'}
              </PrimaryButton>
            </div>
          }
        >
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Page name">
              <input
                className={inputCls}
                value={draft.title}
                onChange={(e) => onDraftChange({ title: e.target.value })}
              />
            </Field>
            <Field label="Address" hint={`Visitors reach this page at /${draft.slug}`}>
              <input
                className={inputCls}
                value={draft.slug}
                onChange={(e) => onDraftChange({ slug: e.target.value })}
              />
            </Field>
            <Field label="Navigation label" hint="Defaults to the page name.">
              <input
                className={inputCls}
                value={draft.navLabel}
                onChange={(e) => onDraftChange({ navLabel: e.target.value })}
              />
            </Field>
            <div className="flex flex-col justify-center gap-2">
              <Toggle
                checked={draft.showInNav}
                onChange={(v) => onDraftChange({ showInNav: v })}
                label="Show in navigation"
              />
              <Toggle
                checked={draft.isPublished}
                onChange={(v) => onDraftChange({ isPublished: v })}
                label={selected.is_home ? 'Published (the landing page is always live)' : 'Published'}
              />
            </div>
            <Field label="SEO title" hint="Shown in search results. Defaults to the page name.">
              <input
                className={inputCls}
                value={draft.seoTitle}
                onChange={(e) => onDraftChange({ seoTitle: e.target.value })}
              />
            </Field>
            <Field label="SEO description">
              <input
                className={inputCls}
                value={draft.seoDescription}
                onChange={(e) => onDraftChange({ seoDescription: e.target.value })}
              />
            </Field>
          </div>

          <div className="mt-6">
            <BlockList blocks={draft.blocks} onChange={(blocks) => onDraftChange({ blocks })} />
          </div>

          <div className="mt-4 rounded border border-dashed border-forest/25 p-3">
            <p className="mb-2 text-xs uppercase tracking-wide text-ink/60">Add a section</p>
            <div className="flex flex-wrap gap-2">
              {BLOCK_TYPES.map((meta) => (
                <SecondaryButton
                  key={meta.type}
                  title={meta.description}
                  onClick={() => onDraftChange({ blocks: [...draft.blocks, newBlock(meta)] })}
                >
                  + {meta.label}
                </SecondaryButton>
              ))}
            </div>
          </div>
        </Panel>
      )}
    </div>
  );
}
