'use client';

import { useState } from 'react';
import type { StoreSite, StoreSiteHoursEntry, StoreSiteSocialLink } from '@alqove/api-client';
import { DAY_NAMES } from '@/components/storefront/hours';
import { firstError, useSiteMutations } from './use-store-site';
import { ErrorText, Field, inputCls, Panel, PrimaryButton, SecondaryButton, Toggle } from './ui';

const SOCIAL_PLATFORMS = [
  'instagram',
  'facebook',
  'tiktok',
  'x',
  'pinterest',
  'youtube',
  'website',
] as const;

/** Monday-first for editing, even though `day` is 0 = Sunday on the wire. */
const EDIT_ORDER = [1, 2, 3, 4, 5, 6, 0];

function hoursFrom(site: StoreSite): StoreSiteHoursEntry[] {
  const byDay = new Map<number, StoreSiteHoursEntry>();
  for (const entry of site.hours ?? []) {
    if (typeof entry?.day === 'number') byDay.set(entry.day, entry);
  }

  return EDIT_ORDER.map(
    (day) =>
      byDay.get(day) ?? { day, closed: day === 0, open: '10:00', close: '18:00' },
  );
}

export function DetailsPanel({ storeId, site }: { storeId: string; site: StoreSite }) {
  const { updateSite } = useSiteMutations(storeId);

  const [tagline, setTagline] = useState(site.tagline ?? '');
  const [logoUrl, setLogoUrl] = useState(site.logo_url ?? '');
  const [email, setEmail] = useState(site.contact_email ?? '');
  const [phone, setPhone] = useState(site.contact_phone ?? '');
  const [directions, setDirections] = useState(site.directions_note ?? '');
  const [seoTitle, setSeoTitle] = useState(site.seo_title ?? '');
  const [seoDescription, setSeoDescription] = useState(site.seo_description ?? '');
  const [ogImage, setOgImage] = useState(site.og_image_url ?? '');
  const [hours, setHours] = useState<StoreSiteHoursEntry[]>(() => hoursFrom(site));
  const [socials, setSocials] = useState<StoreSiteSocialLink[]>(site.social_links ?? []);
  const [savedAt, setSavedAt] = useState<string | null>(null);

  function setDay(day: number, patch: Partial<StoreSiteHoursEntry>) {
    setHours((current) => current.map((h) => (h.day === day ? { ...h, ...patch } : h)));
  }

  function save() {
    updateSite.mutate(
      {
        tagline: tagline || null,
        logo_url: logoUrl || null,
        contact_email: email || null,
        contact_phone: phone || null,
        directions_note: directions || null,
        seo_title: seoTitle || null,
        seo_description: seoDescription || null,
        og_image_url: ogImage || null,
        hours,
        social_links: socials.filter((s) => s.url?.trim()),
      },
      { onSuccess: () => setSavedAt(new Date().toLocaleTimeString()) },
    );
  }

  return (
    <div className="space-y-6">
      <Panel
        title="Store details"
        description="Shared content your pages read from — edit it once here."
        actions={
          <div className="flex items-center gap-3">
            {savedAt && <span className="text-xs text-ink/60">Saved at {savedAt}</span>}
            <PrimaryButton onClick={save} disabled={updateSite.isPending}>
              {updateSite.isPending ? 'Saving…' : 'Save details'}
            </PrimaryButton>
          </div>
        }
      >
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Tagline" hint="One line under your name in the footer.">
            <input className={inputCls} value={tagline} onChange={(e) => setTagline(e.target.value)} />
          </Field>
          <Field label="Logo URL" hint="Shown in the site header. Falls back to your store logo.">
            <input
              className={inputCls}
              placeholder="https://…"
              value={logoUrl}
              onChange={(e) => setLogoUrl(e.target.value)}
            />
          </Field>
          <Field label="Contact email">
            <input
              className={inputCls}
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </Field>
          <Field label="Contact phone">
            <input className={inputCls} value={phone} onChange={(e) => setPhone(e.target.value)} />
          </Field>
          <div className="sm:col-span-2">
            <Field label="Directions note" hint="Parking, the entrance, transit — anything a first-time visitor needs.">
              <textarea
                rows={3}
                className={inputCls}
                value={directions}
                onChange={(e) => setDirections(e.target.value)}
              />
            </Field>
          </div>
        </div>
      </Panel>

      <Panel title="Opening hours" description="Used by every hours section on your site.">
        <div className="space-y-2">
          {hours.map((row) => (
            <div key={row.day} className="grid items-center gap-2 sm:grid-cols-[8rem_1fr_1fr_9rem]">
              <span className="text-sm font-medium">{DAY_NAMES[row.day ?? 0]}</span>
              <input
                type="time"
                className={inputCls}
                aria-label={`${DAY_NAMES[row.day ?? 0]} opening time`}
                disabled={row.closed ?? false}
                value={row.open ?? ''}
                onChange={(e) => setDay(row.day ?? 0, { open: e.target.value })}
              />
              <input
                type="time"
                className={inputCls}
                aria-label={`${DAY_NAMES[row.day ?? 0]} closing time`}
                disabled={row.closed ?? false}
                value={row.close ?? ''}
                onChange={(e) => setDay(row.day ?? 0, { close: e.target.value })}
              />
              <Toggle
                checked={row.closed ?? false}
                onChange={(v) => setDay(row.day ?? 0, { closed: v })}
                label="Closed"
              />
            </div>
          ))}
        </div>
      </Panel>

      <Panel
        title="Social links"
        actions={
          <SecondaryButton
            onClick={() => setSocials([...socials, { platform: 'instagram', url: '' }])}
            disabled={socials.length >= 8}
          >
            + Add link
          </SecondaryButton>
        }
      >
        {socials.length === 0 ? (
          <p className="text-sm text-ink/60">No social links yet.</p>
        ) : (
          <div className="space-y-2">
            {socials.map((link, i) => (
              <div key={i} className="grid gap-2 sm:grid-cols-[10rem_1fr_auto]">
                <select
                  className={inputCls}
                  aria-label="Platform"
                  value={link.platform ?? 'instagram'}
                  onChange={(e) =>
                    setSocials(
                      socials.map((s, j) =>
                        i === j
                          ? { ...s, platform: e.target.value as StoreSiteSocialLink['platform'] }
                          : s,
                      ),
                    )
                  }
                >
                  {SOCIAL_PLATFORMS.map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
                <input
                  className={inputCls}
                  placeholder="https://…"
                  value={link.url ?? ''}
                  onChange={(e) =>
                    setSocials(socials.map((s, j) => (i === j ? { ...s, url: e.target.value } : s)))
                  }
                />
                <SecondaryButton onClick={() => setSocials(socials.filter((_, j) => j !== i))}>
                  Remove
                </SecondaryButton>
              </div>
            ))}
          </div>
        )}
      </Panel>

      <Panel title="Search engines" description="How your site appears in search results and link previews.">
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Default title">
            <input
              className={inputCls}
              value={seoTitle}
              onChange={(e) => setSeoTitle(e.target.value)}
            />
          </Field>
          <Field label="Share image URL" hint="1200 × 630 works best.">
            <input
              className={inputCls}
              placeholder="https://…"
              value={ogImage}
              onChange={(e) => setOgImage(e.target.value)}
            />
          </Field>
          <div className="sm:col-span-2">
            <Field label="Default description">
              <textarea
                rows={2}
                className={inputCls}
                value={seoDescription}
                onChange={(e) => setSeoDescription(e.target.value)}
              />
            </Field>
          </div>
        </div>
        <div className="mt-4">
          <PrimaryButton onClick={save} disabled={updateSite.isPending}>
            {updateSite.isPending ? 'Saving…' : 'Save details'}
          </PrimaryButton>
        </div>
        <ErrorText>{firstError(updateSite.error)}</ErrorText>
      </Panel>
    </div>
  );
}
