'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import {
  getMe,
  getStoreSettings,
  selectStoreTemplate,
  updateStoreContent,
  publishStore,
  StoreSettings,
} from '@/lib/api/agent'
import { STORE_TEMPLATES, StoreTemplate } from '@/lib/storefront/templates'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Skeleton } from '@/components/ui/Skeleton'
import { ErrorState } from '@/components/ui/ErrorState'
import { useToast } from '@/components/ui/Toast'
import { CheckCircle2, XCircle, Circle, ExternalLink, Rocket, Settings2, Store } from 'lucide-react'

function TemplateMiniPreview({ t }: { t: StoreTemplate }) {
  const p = t.palette
  const headingFont =
    t.tokens.headingFont === 'serif' ? 'font-serif'
    : t.tokens.headingFont === 'mono' ? 'font-mono'
    : t.tokens.headingFont === 'display' ? 'font-black tracking-tight' : 'font-sans font-bold'
  const heroLabel = t.tokens.hero === 'asymmetric' ? 'ASYM' : t.tokens.hero === 'immersive' ? 'IMMER' : t.tokens.hero === 'fullbleed' ? 'FULL' : t.tokens.hero === 'trust' ? 'TRUST' : t.tokens.hero.toUpperCase().slice(0,4)
  const navDots = t.tokens.navStyle === 'centered' ? 'justify-center' : t.tokens.navStyle === 'minimal' ? 'justify-between opacity-60' : t.tokens.navStyle === 'floating' ? 'justify-between px-2' : 'justify-between'
  const heroH = t.tokens.heroHeight === 'cinematic' ? 'h-10' : t.tokens.heroHeight === 'immersive' ? 'h-12' : t.tokens.heroHeight === 'compact' ? 'h-6' : 'h-8'
  const cardRadius = t.tokens.radius === 'pill' ? 999 : t.tokens.radius === 'large' ? 8 : t.tokens.radius === 'none' ? 0 : 4
  const gridCols = t.tokens.productGrid === 'dense' ? 3 : t.tokens.productGrid === 'sparse' ? 2 : t.tokens.productGrid === 'four-column' ? 4 : 3

  return (
    <div
      className="h-40 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 flex flex-col shadow-sm"
      style={{ background: p.background }}
      aria-hidden
    >
      {/* Nav */}
      <div className={`h-6 flex items-center px-2 gap-1 shrink-0 border-b ${t.tokens.navStyle === 'floating' ? 'm-1 rounded-full' : ''}`} style={{ background: t.tokens.navStyle === 'floating' ? p.surface : p.surface, borderColor: p.surface }}>
        <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ background: p.primary }} />
        <span className={`hidden sm:flex flex-1 gap-1 items-center ${navDots}`}>
          <span className="h-1 w-6 rounded-full" style={{ background: p.text, opacity: 0.25 }} />
          <span className="h-1 w-4 rounded-full hidden md:block" style={{ background: p.text, opacity: 0.15 }} />
          <span className="h-1 w-5 rounded-full hidden lg:block" style={{ background: p.text, opacity: 0.15 }} />
        </span>
        <span className="ml-auto h-2 w-2 rounded-full lg:h-1.5 lg:w-8" style={{ background: p.accent }} />
      </div>

      {/* Hero - composition-aware */}
      <div className={`relative flex-1 flex overflow-hidden ${t.tokens.heroComposition === 'text-center' ? 'items-center justify-center text-center' : t.tokens.heroComposition === 'text-right' ? 'items-center justify-end text-right' : t.tokens.heroComposition === 'asymmetric' ? 'items-stretch' : 'items-center' } ${heroH}`} style={{ background: `linear-gradient(${p.gradientAngle || 135}deg, ${p.gradientStart || p.primary}, ${p.gradientEnd || p.accent})` }}>
        {t.tokens.heroComposition === 'asymmetric' ? (
          <>
            <div className="flex-1 p-2 flex flex-col justify-center">
              <span className={`text-[7px] font-bold tracking-widest uppercase px-1.5 py-0.5 rounded-full w-fit`} style={{ background: 'rgba(255,255,255,0.9)', color: p.primary }}>{heroLabel}</span>
              <span className={`mt-1 text-[9px] leading-none ${headingFont} text-white`}>Hero</span>
            </div>
            <div className="w-1/2 h-full p-1">
              <div className="w-full h-full rounded-sm" style={{ background: 'rgba(255,255,255,0.85)', borderRadius: cardRadius }} />
            </div>
          </>
        ) : t.tokens.hero === 'banner' ? (
          <div className="w-full px-2 py-1 text-center">
            <span className="text-[7px] font-bold tracking-widest uppercase text-white/80">BANNER</span>
            <div className={`text-[9px] ${headingFont} text-white leading-none mt-0.5`}>Bold headline</div>
          </div>
        ) : (
          <div className={`w-full px-2 ${t.tokens.heroComposition === 'text-center' ? 'text-center' : ''}`}>
            <span className="text-[6px] font-semibold tracking-widest uppercase text-white/70">{heroLabel} • {t.tokens.headingFont}</span>
            <div className={`text-[9px] ${headingFont} ${t.tokens.uppercaseHeadings ? 'uppercase tracking-wide' : ''} text-white leading-tight mt-0.5 line-clamp-1`}>
              {t.tokens.headingFont === 'serif' ? 'Elegant Serif' : t.tokens.headingFont === 'display' ? 'BOLD DISPLAY' : t.tokens.headingFont === 'mono' ? 'mono_heading' : 'Modern Store'}
            </div>
          </div>
        )}
        <span className="absolute bottom-0 left-0 right-0 h-0.5" style={{ background: p.accent, opacity: 0.7 }} aria-hidden />
      </div>

      {/* Categories hint */}
      <div className="px-2 pt-1.5 pb-1 flex gap-1 items-center">
        {t.tokens.categoryStyle === 'chips' || t.tokens.categoryStyle === 'pill-grid' ? (
          <>
            <span className="h-2 px-1.5 rounded-full text-[6px] font-bold flex items-center" style={{ background: p.primary, color: '#fff' }}>CAT</span>
            <span className="h-2 w-6 rounded-full" style={{ background: p.surface, border: `1px solid ${p.text}12` }} />
            <span className="h-2 w-4 rounded-full hidden sm:block" style={{ background: p.surface }} />
          </>
        ) : t.tokens.categoryStyle === 'overlay-grid' ? (
          <>
            <span className="h-3 w-8 rounded-sm" style={{ background: p.surface }} />
            <span className="h-3 w-8 rounded-sm" style={{ background: p.surface }} />
            <span className="h-3 flex-1 rounded-sm" style={{ background: p.primary, opacity: 0.15 }} />
          </>
        ) : (
          <>
            <span className="h-1.5 w-3 rounded-full" style={{ background: p.text, opacity: 0.2 }} />
            <span className="h-1.5 w-8 rounded-full" style={{ background: p.primary, opacity: 0.12 }} />
          </>
        )}
        <span className="ml-auto text-[6px] font-medium opacity-40">{t.tokens.density}</span>
      </div>

      {/* Product grid miniature */}
      <div className="flex-1 px-2 pb-2">
        <div className="grid gap-1 h-full" style={{ gridTemplateColumns: `repeat(${gridCols}, 1fr)` }}>
          {[...Array(gridCols === 4 ? 4 : 3)].map((_, i) => (
            <div key={i} className="flex flex-col gap-1 p-1" style={{ background: t.tokens.card === 'outline' ? 'transparent' : t.tokens.card === 'minimal' ? 'transparent' : p.surface, border: t.tokens.card === 'outline' || t.tokens.card === 'blocky' ? `1px solid ${p.text}14` : 'none', borderRadius: cardRadius, boxShadow: t.tokens.shadow === 'strong' ? '0 1px 3px rgba(0,0,0,0.15)' : t.tokens.shadow === 'dramatic' ? '0 4px 12px rgba(0,0,0,0.15)' : 'none' }}>
              <div className="flex-1 rounded-sm" style={{ background: i === 0 ? `linear-gradient(135deg, ${p.primary}18, ${p.accent}18)` : p.background, borderRadius: Math.max(0, cardRadius-2), minHeight: 14 }} />
              <div className="h-1 w-3/4 rounded-full" style={{ background: p.text, opacity: 0.6 }} />
              <div className="h-1 w-1/2 rounded-full" style={{ background: p.primary, opacity: 0.7 }} />
            </div>
          ))}
        </div>
      </div>

      {/* Footer + palette */}
      <div className="h-5 flex items-center px-2 gap-1 shrink-0 border-t" style={{ background: t.tokens.footer.startsWith('dark') || t.tokens.footer === 'brand-band' ? p.text : p.surface, borderColor: 'transparent' }}>
        <span className="h-1 w-1 rounded-full" style={{ background: t.tokens.footer.startsWith('dark') ? '#fff' : p.text, opacity: 0.3 }} />
        <span className="h-1 flex-1 rounded-full" style={{ background: t.tokens.footer.startsWith('dark') ? 'rgba(255,255,255,0.15)' : p.text, opacity: 0.08 }} />
        <span className="flex items-center gap-0.5 ml-auto">
          <span className="w-2 h-2 rounded-full border border-white/30" style={{ background: p.primary }} title={p.primary} />
          <span className="w-2 h-2 rounded-full border border-white/30" style={{ background: p.accent }} title={p.accent} />
          <span className="w-2 h-2 rounded-full border border-white/30 hidden sm:block" style={{ background: p.secondary }} title={p.secondary} />
        </span>
      </div>
    </div>
  )
}

export default function StorePage() {
  const { toast } = useToast()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isAdmin, setIsAdmin] = useState(false)
  const [slug, setSlug] = useState<string | null>(null)
  const [settings, setSettings] = useState<StoreSettings | null>(null)
  const [busyId, setBusyId] = useState<string | null>(null)
  const [showCustomize, setShowCustomize] = useState(false)
  const [draft, setDraft] = useState<Record<string, string>>({})
  const [savingContent, setSavingContent] = useState(false)

  const refresh = useCallback(() => {
    getStoreSettings().then(res => {
      if (!res.success) setError(res.message)
      else {
        setSettings(res.data)
        const c = res.data.config || {}
        setDraft({
          accent_color: String(c.accent_color ?? ''),
          promo_text: String(c.promo_text ?? ''),
          story_title: String(c.story_title ?? ''),
          story_body: String(c.story_body ?? ''),
          opening_hours: String(c.opening_hours ?? ''),
          hero_image_url: String(c.hero_image_url ?? ''),
          about_image_url: String(c.about_image_url ?? ''),
          badges: Array.isArray(c.badges) ? (c.badges as string[]).join(', ') : '',
          testimonials: Array.isArray(c.testimonials)
            ? (c.testimonials as Array<Record<string, string>>).map(t => `${t.author ?? ''} | ${t.text ?? ''}`).join('\n') : '',
          faqs: Array.isArray(c.faqs)
            ? (c.faqs as Array<Record<string, string>>).map(f => `${f.question ?? ''} | ${f.answer ?? ''}`).join('\n') : '',
          stats: Array.isArray(c.stats)
            ? (c.stats as Array<Record<string, string>>).map(s => `${s.value ?? ''} | ${s.label ?? ''}`).join('\n') : '',
        })
      }
      setLoading(false)
    })
  }, [])

  useEffect(() => {
    getMe().then(me => {
      if (me.success && me.data.role === 'admin') {
        setIsAdmin(true)
        setSlug(me.data.business_slug)
        refresh()
      } else if (me.success) {
        setLoading(false)
      } else {
        setError(me.message)
        setLoading(false)
      }
    })
  }, [refresh])

  if (loading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-40 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    )
  }

  if (!isAdmin) {
    return <ErrorState title="Admin access required" message="Only business admins can manage the storefront template." />
  }

  if (error) {
    return <ErrorState title="Could not load store settings" message={error} onRetry={() => { setLoading(true); setError(null); refresh() }} />
  }

  const current = settings
    ? STORE_TEMPLATES.find(t => t.id === settings.template_id) || STORE_TEMPLATES[0]
    : STORE_TEMPLATES[0]
  const readiness = settings?.readiness

  const handleSelect = async (t: StoreTemplate) => {
    setBusyId(t.id)
    const res = await selectStoreTemplate(t.id)
    setBusyId(null)
    if (!res.success) {
      const missing = (res as { details?: { missing_required?: string[] } }).details?.missing_required
      toast({
        title: 'Template needs more information',
        description: missing?.length
          ? `Missing: ${missing.join(', ')}`
          : res.message,
        variant: 'destructive',
      })
      return
    }
    toast({ title: `Template changed`, description: `Your storefront now uses ${t.name}.` })
    refresh()
  }

  const handlePublish = async () => {
    setBusyId('publish')
    const res = await publishStore()
    setBusyId(null)
    if (!res.success) {
      const missing = (res as { details?: { missing_required?: string[] } }).details?.missing_required
      toast({
        title: 'Cannot publish yet',
        description: missing?.length ? `Missing: ${missing.join(', ')}` : res.message,
        variant: 'destructive',
      })
      return
    }
    toast({ title: 'Store published', description: 'Customers can now see your storefront.' })
    refresh()
  }

  const parseLines = (raw: string, keys: [string, string]) =>
    raw.split('\n').map(l => l.trim()).filter(Boolean).map(line => {
      const [a, ...rest] = line.split('|')
      return { [keys[0]]: a.trim(), [keys[1]]: rest.join('|').trim() }
    }).filter(o => Object.values(o).some(v => v))

  const handleSaveContent = async () => {
    setSavingContent(true)
    const config: Record<string, unknown> = {
      accent_color: draft.accent_color || null,
      promo_text: draft.promo_text || null,
      story_title: draft.story_title || null,
      story_body: draft.story_body || null,
      opening_hours: draft.opening_hours || null,
      hero_image_url: draft.hero_image_url || null,
      about_image_url: draft.about_image_url || null,
      badges: draft.badges ? draft.badges.split(',').map(s => s.trim()).filter(Boolean) : [],
      testimonials: parseLines(draft.testimonials, ['author', 'text']),
      faqs: parseLines(draft.faqs, ['question', 'answer']),
      stats: parseLines(draft.stats, ['value', 'label']),
    }
    const res = await updateStoreContent(config)
    setSavingContent(false)
    if (!res.success) {
      toast({ title: 'Could not save content', description: res.message, variant: 'destructive' })
      return
    }
    toast({ title: 'Store content saved' })
    refresh()
  }

  const setDraftField = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
    setDraft(d => ({ ...d, [k]: e.target.value }))

  return (
    <div className="space-y-6">
      {/* Current template */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Store className="h-5 w-5" /> Your Storefront</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col md:flex-row md:items-center gap-4 justify-between">
            <div>
              <p className="text-sm text-gray-500 dark:text-gray-400">Current template</p>
              <p className="text-xl font-bold">{current.name}</p>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{current.description}</p>
              <div className="mt-2 flex items-center gap-2">
                {settings?.published
                  ? <Badge variant="success">Published</Badge>
                  : <Badge variant="warning">Not published</Badge>}
                <Badge variant="secondary">v{current.version}</Badge>
              </div>
            </div>
            <div className="flex flex-wrap gap-2">
              {slug && (
                <a href={`/shop/${slug}`} target="_blank" rel="noreferrer">
                  <Button variant="outline"><ExternalLink className="h-4 w-4 mr-2" /> Preview Store</Button>
                </a>
              )}
              <Button onClick={handlePublish} loading={busyId === 'publish'} disabled={!readiness?.ready_to_publish}>
                <Rocket className="h-4 w-4 mr-2" /> Publish Store
              </Button>
            </div>
          </div>

          {/* Readiness */}
          {readiness && (
            <div className="mt-6 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
              <p className="font-semibold mb-3">Store readiness</p>
              {!readiness.ready_to_publish && (
                <p className="mb-3 text-sm font-medium text-amber-700 dark:text-amber-300">
                  Your store needs {readiness.missing_required.length} more item{readiness.missing_required.length === 1 ? '' : 's'} before it can be published:{' '}
                  {readiness.missing_required.join(', ')}.
                </p>
              )}
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-2">
                {readiness.required_checks.map(c => (
                  <div key={c.key} className="flex items-center gap-2 text-sm">
                    {c.met
                      ? <CheckCircle2 className="h-4 w-4 text-green-600 shrink-0" />
                      : <XCircle className="h-4 w-4 text-red-500 shrink-0" />}
                    <span className={!c.met ? 'font-medium' : ''}>{c.label}</span>
                  </div>
                ))}
              </div>
              {readiness.optional_content.some(o => o.present) && (
                <div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-800 flex flex-wrap gap-x-4 gap-y-1">
                  {readiness.optional_content.filter(o => o.present).map(o => (
                    <span key={o.key} className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
                      <Circle className="h-2.5 w-2.5 fill-current" /> {o.label}
                    </span>
                  ))}
                </div>
              )}
              <p className="mt-3 text-xs text-gray-400">
                Catalog: {readiness.catalog_stats.published_products} products · {readiness.catalog_stats.categories} categories · {readiness.catalog_stats.products_with_images} with images
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Customize */}
      <Card>
        <CardHeader>
          <button className="flex items-center gap-2 w-full text-left" onClick={() => setShowCustomize(s => !s)} aria-expanded={showCustomize}>
            <Settings2 className="h-5 w-5" />
            <CardTitle>Customize content</CardTitle>
            <span className="ml-auto text-sm text-gray-400">{showCustomize ? 'Hide' : 'Show'}</span>
          </button>
        </CardHeader>
        {showCustomize && (
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium">Accent color</label>
                <Input type="color" value={/^#[0-9a-fA-F]{6}$/.test(draft.accent_color) ? draft.accent_color : '#f97316'} onChange={setDraftField('accent_color')} className="h-10 mt-1" />
                <Input placeholder="#f97316 (optional)" value={draft.accent_color} onChange={setDraftField('accent_color')} className="mt-2" />
              </div>
              <div>
                <label className="text-sm font-medium">Promotional banner text</label>
                <Input value={draft.promo_text} onChange={setDraftField('promo_text')} placeholder="e.g. Free delivery over 100,000 RWF" className="mt-1" />
              </div>
              <div>
                <label className="text-sm font-medium">Opening hours</label>
                <Input value={draft.opening_hours} onChange={setDraftField('opening_hours')} placeholder="Mon–Sat, 8:00–18:00" className="mt-1" />
              </div>
              <div>
                <label className="text-sm font-medium">Hero image URL</label>
                <Input value={draft.hero_image_url} onChange={setDraftField('hero_image_url')} placeholder="https://…" className="mt-1" />
              </div>
              <div>
                <label className="text-sm font-medium">About image URL</label>
                <Input value={draft.about_image_url} onChange={setDraftField('about_image_url')} placeholder="https://…" className="mt-1" />
              </div>
              <div>
                <label className="text-sm font-medium">Trust badges (comma-separated)</label>
                <Input value={draft.badges} onChange={setDraftField('badges')} placeholder="Secure checkout, Fast delivery" className="mt-1" />
              </div>
            </div>
            <div>
              <label className="text-sm font-medium">Business story</label>
              <textarea className="w-full mt-1 rounded-md border border-gray-300 dark:border-gray-600 bg-transparent p-3 text-sm min-h-[80px]" value={draft.story_title} hidden readOnly aria-hidden />
              <Input value={draft.story_title} onChange={setDraftField('story_title')} placeholder="Story title (optional)" className="mt-1" />
              <textarea className="w-full mt-2 rounded-md border border-gray-300 dark:border-gray-600 bg-transparent p-3 text-sm min-h-[90px]" value={draft.story_body} onChange={setDraftField('story_body')} placeholder="Tell customers the story behind your business…" />
            </div>
            <div className="grid md:grid-cols-3 gap-4">
              <div>
                <label className="text-sm font-medium">Testimonials</label>
                <p className="text-xs text-gray-400 mb-1">One per line: Author | Quote</p>
                <textarea className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-transparent p-3 text-sm min-h-[90px]" value={draft.testimonials} onChange={setDraftField('testimonials')} />
              </div>
              <div>
                <label className="text-sm font-medium">FAQs</label>
                <p className="text-xs text-gray-400 mb-1">One per line: Question | Answer</p>
                <textarea className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-transparent p-3 text-sm min-h-[90px]" value={draft.faqs} onChange={setDraftField('faqs')} />
              </div>
              <div>
                <label className="text-sm font-medium">Statistics</label>
                <p className="text-xs text-gray-400 mb-1">One per line: Value | Label</p>
                <textarea className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-transparent p-3 text-sm min-h-[90px]" value={draft.stats} onChange={setDraftField('stats')} />
              </div>
            </div>
            <div className="flex justify-end">
              <Button onClick={handleSaveContent} loading={savingContent}>Save Content</Button>
            </div>
          </CardContent>
        )}
      </Card>

      {/* Library */}
      <Card>
        <CardHeader>
          <CardTitle>Template library</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid sm:grid-cols-2 xl:grid-cols-3 gap-5">
            {STORE_TEMPLATES.map(t => {
              const isCurrent = settings?.template_id === t.id
              return (
                <div key={t.id} className={`rounded-lg border p-4 flex flex-col gap-3 ${isCurrent ? 'border-indigo-500 ring-1 ring-indigo-500' : 'border-gray-200 dark:border-gray-700'}`}>
                  <TemplateMiniPreview t={t} />
                  <div>
                    <div className="flex items-center gap-2">
                      <p className="font-semibold">{String(t.index).padStart(2, '0')} · {t.name}</p>
                      {isCurrent && <Badge variant="default">Current</Badge>}
                    </div>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{t.description}</p>
                    <p className="text-xs text-gray-400 mt-1">Best for: {t.bestFor.join(', ')}</p>
                  </div>
                  <div className="mt-auto flex gap-2">
                    {slug && (
                      <a href={`/shop/${slug}?preview=${t.id}`} target="_blank" rel="noreferrer" className="flex-1">
                        <Button variant="outline" className="w-full">Preview</Button>
                      </a>
                    )}
                    <Button
                      className="flex-1"
                      variant={isCurrent ? 'secondary' : 'primary'}
                      disabled={isCurrent || busyId === t.id}
                      loading={busyId === t.id}
                      onClick={() => handleSelect(t)}
                    >
                      {isCurrent ? 'In use' : 'Use Template'}
                    </Button>
                  </div>
                </div>
              )
            })}
          </div>
          <p className="mt-4 text-xs text-gray-400">
            Preview uses your real store data and is visible only to you while signed in as an admin of this business. Switching templates never changes your products, prices, orders, or customers. Manage brand identity under <Link href="/dashboard/settings" className="underline">Settings</Link>.
          </p>
        </CardContent>
      </Card>
    </div>
  )
}
