'use client'

import { useEffect, useState } from 'react'
import QRCode from 'qrcode'
import {
  getMe,
  updateBusinessSettings,
  BusinessSettingsInput,
} from '@/lib/api/agent'
import { AGENT_API_URL } from '@/lib/api/config'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
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 { Copy, ExternalLink, QrCode, Save, Store } from 'lucide-react'
import { cn } from '@/lib/utils'

interface SettingsForm {
  name: string
  description: string
  logo_url: string
  hero_title: string
  hero_subtitle: string
  brand_color: string
  address: string
  phone: string
  email: string
  maps_url: string
  whatsapp: string
  website_url: string
  show_about: boolean
  show_contact: boolean
  payment_enabled: boolean
  payment_phone: string
  delivery_fee: string
  free_delivery_above: string
  tax_rate_pct: string
}

const EMPTY_FORM: SettingsForm = {
  name: '',
  description: '',
  logo_url: '',
  hero_title: '',
  hero_subtitle: '',
  brand_color: '#4f46e5',
  address: '',
  phone: '',
  email: '',
  maps_url: '',
  whatsapp: '',
  website_url: '',
  show_about: true,
  show_contact: true,
  payment_enabled: false,
  payment_phone: '',
  delivery_fee: '',
  free_delivery_above: '',
  tax_rate_pct: '',
}

export default function StoreSettingsPage() {
  const { toast } = useToast()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [role, setRole] = useState<'admin' | 'stock_keeper' | null>(null)
  const [slug, setSlug] = useState<string | null>(null)
  const [businessName, setBusinessName] = useState<string | null>(null)
  const [form, setForm] = useState<SettingsForm>(EMPTY_FORM)
  const [saving, setSaving] = useState(false)
  const [qrDataUrl, setQrDataUrl] = useState<string | null>(null)
  const [restockMode, setRestockMode] = useState<'auto' | 'manual'>('auto')

  useEffect(() => {
    getMe().then(res => {
      if (!res.success) {
        setError(res.message)
        setLoading(false)
        return
      }
      setRole(res.data.role)
      setSlug(res.data.business_slug)
      setBusinessName(res.data.business_name)
      setRestockMode(res.data.restock_mode ?? 'auto')
      if (res.data.role !== 'admin') {
        setLoading(false)
        return
      }
      // Prefill from the public shop config (authoritative current values).
      fetch(
        `${AGENT_API_URL}/shop/${res.data.business_slug}/config`
      )
        .then(r => r.json())
        .then(body => {
          if (!body.success) return
          const b = body.data.branding || {}
          setForm({
            name: b.name ?? businessName ?? '',
            description: b.description ?? '',
            logo_url: b.logo_url ?? '',
            hero_title: b.hero_title ?? '',
            hero_subtitle: b.hero_subtitle ?? '',
            brand_color: b.brand_color || '#4f46e5',
            address: b.address ?? '',
            phone: b.phone ?? '',
            email: b.email ?? '',
            maps_url: b.maps_url ?? '',
            whatsapp: b.whatsapp ?? '',
            website_url: b.website_url ?? '',
            show_about: b.show_about !== false,
            show_contact: b.show_contact !== false,
            payment_enabled: b.payment_enabled === true,
            payment_phone: b.payment_phone ?? '',
            delivery_fee:
              body.data.delivery_fee != null ? String(body.data.delivery_fee) : '',
            free_delivery_above:
              body.data.free_delivery_threshold != null
                ? String(body.data.free_delivery_threshold)
                : '',
            tax_rate_pct:
              body.data.tax_rate_pct != null ? String(body.data.tax_rate_pct) : '',
          })
        })
        .catch(() => {})
        .finally(() => setLoading(false))
    })
  }, [])

  const storeUrl =
    typeof window !== 'undefined' && slug
      ? `${window.location.origin}/shop/${slug}`
      : slug
        ? `/shop/${slug}`
        : ''

  async function generateQr() {
    if (!storeUrl) return
    try {
      const url = await QRCode.toDataURL(storeUrl, { width: 320, margin: 2 })
      setQrDataUrl(url)
    } catch {
      toast({ title: 'Could not generate QR code', variant: 'destructive' })
    }
  }

  function update<K extends keyof SettingsForm>(key: K, value: SettingsForm[K]) {
    setForm(f => ({ ...f, [key]: value }))
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true)
    const payload: BusinessSettingsInput = {}
    if (form.name.trim() !== '') payload.name = form.name.trim()
    if (form.description !== '') payload.description = form.description
    if (form.logo_url !== '') payload.logo_url = form.logo_url
    if (form.hero_title !== '') payload.hero_title = form.hero_title
    if (form.hero_subtitle !== '') payload.hero_subtitle = form.hero_subtitle
    if (/^#[0-9a-fA-F]{6}$/.test(form.brand_color)) payload.brand_color = form.brand_color
    if (form.address !== '') payload.address = form.address
    if (form.phone !== '') payload.phone = form.phone
    if (form.email !== '') payload.email = form.email
    if (form.maps_url !== '') payload.maps_url = form.maps_url
    if (form.whatsapp !== '') payload.whatsapp = form.whatsapp
    if (form.website_url !== '') payload.website_url = form.website_url
    payload.show_about = form.show_about
    payload.show_contact = form.show_contact
    payload.payment_enabled = form.payment_enabled
    if (form.payment_phone !== '') payload.payment_phone = form.payment_phone
    if (form.delivery_fee !== '') payload.delivery_fee = Number(form.delivery_fee)
    if (form.free_delivery_above !== '')
      payload.free_delivery_above = Number(form.free_delivery_above)
    if (form.tax_rate_pct !== '') payload.tax_rate_pct = Number(form.tax_rate_pct)
    payload.restock_mode = restockMode

    const res = await updateBusinessSettings(payload)
    setSaving(false)
    if (!res.success) {
      toast({ title: res.message, variant: 'destructive' })
      return
    }
    toast({
      title: 'Store settings saved',
      description: 'Your storefront reflects the changes immediately.',
      variant: 'success',
    })
  }

  async function copyLink() {
    try {
      await navigator.clipboard.writeText(storeUrl)
      toast({ title: 'Store link copied', variant: 'success' })
    } catch {
      toast({ title: 'Copy failed — select and copy manually', variant: 'destructive' })
    }
  }

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

  if (error) return <ErrorState message={error} />

  if (role !== 'admin') {
    return (
      <ErrorState message="Only the business admin can manage store settings." />
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Store Settings</h1>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          Branding and storefront configuration for {businessName}.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <Store className="h-5 w-5" /> Your Store
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap items-center gap-3">
            <code className="rounded bg-gray-100 dark:bg-gray-800 px-3 py-2 text-sm">
              {storeUrl}
            </code>
            <Button type="button" size="sm" variant="outline" onClick={copyLink}>
              <Copy className="h-4 w-4 mr-1" /> Copy Link
            </Button>
            <Button type="button" size="sm" variant="outline" onClick={generateQr}>
              <QrCode className="h-4 w-4 mr-1" /> Generate QR Code
            </Button>
            {slug && (
              <a href={`/shop/${slug}`} target="_blank" rel="noreferrer">
                <Button type="button" size="sm" variant="ghost">
                  <ExternalLink className="h-4 w-4 mr-1" /> View Storefront
                </Button>
              </a>
            )}
          </div>
          {qrDataUrl && (
            <div className="flex flex-col items-start gap-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={qrDataUrl} alt={`QR code for ${storeUrl}`} className="h-44 w-44 rounded border border-gray-200 dark:border-gray-700" />
              <p className="text-xs text-gray-500">Print this — customers scan to open your store.</p>
            </div>
          )}
        </CardContent>
      </Card>

      <form onSubmit={handleSave} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Appearance</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-2">
            <div className="md:col-span-2">
              <label className="text-sm font-medium">Hero title</label>
              <Input
                value={form.hero_title}
                onChange={e => update('hero_title', e.target.value)}
                placeholder="Quality Technology for Kigali Businesses"
                maxLength={160}
              />
            </div>
            <div className="md:col-span-2">
              <label className="text-sm font-medium">Hero subtitle</label>
              <Input
                value={form.hero_subtitle}
                onChange={e => update('hero_subtitle', e.target.value)}
                placeholder="Reliable electronics delivered across Kigali"
                maxLength={300}
              />
            </div>
            <div>
              <label className="text-sm font-medium">Brand color</label>
              <div className="flex items-center gap-2">
                <input
                  type="color"
                  value={/^#[0-9a-fA-F]{6}$/.test(form.brand_color) ? form.brand_color : '#4f46e5'}
                  onChange={e => update('brand_color', e.target.value)}
                  className="h-9 w-12 cursor-pointer rounded border border-gray-300 dark:border-gray-600"
                  aria-label="Pick brand color"
                />
                <Input
                  value={form.brand_color}
                  onChange={e => update('brand_color', e.target.value)}
                  placeholder="#2563eb"
                  maxLength={7}
                />
              </div>
            </div>
            <div>
              <label className="text-sm font-medium">Logo URL</label>
              <Input
                value={form.logo_url}
                onChange={e => update('logo_url', e.target.value)}
                placeholder="https://…/logo.png"
                maxLength={500}
              />
            </div>
            <div className="md:col-span-2">
              <label className="text-sm font-medium">Business description</label>
              <textarea
                value={form.description}
                onChange={e => update('description', e.target.value)}
                rows={2}
                maxLength={2000}
                className="w-full rounded-md border border-gray-300 dark:border-gray-600 bg-transparent px-3 py-2 text-sm"
                placeholder="What you sell and what makes you reliable."
              />
            </div>
            <div className="flex items-center gap-6 md:col-span-2">
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={form.show_about}
                  onChange={e => update('show_about', e.target.checked)}
                />
                Show About section
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={form.show_contact}
                  onChange={e => update('show_contact', e.target.checked)}
                />
                Show Contact section
              </label>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Contact & Location</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-2">
            <div>
              <label className="text-sm font-medium">Business name</label>
              <Input
                value={form.name}
                onChange={e => update('name', e.target.value)}
                placeholder="Kigali Audio Source"
                maxLength={200}
              />
            </div>
            <div>
              <label className="text-sm font-medium">Phone number</label>
              <Input
                type="tel"
                value={form.phone}
                onChange={e => update('phone', e.target.value)}
                placeholder="+250788000000"
                maxLength={40}
              />
              <p className="text-xs text-gray-500 mt-1">
                Shown as a call button (tel:) on your storefront.
              </p>
            </div>
            <div>
              <label className="text-sm font-medium">Email</label>
              <Input
                type="email"
                value={form.email}
                onChange={e => update('email', e.target.value)}
                placeholder="hello@example.rw"
                maxLength={160}
              />
              <p className="text-xs text-gray-500 mt-1">
                Shown as a mailto: link for customer inquiries.
              </p>
            </div>
            <div>
              <label className="text-sm font-medium">Maps URL</label>
              <Input
                value={form.maps_url}
                onChange={e => update('maps_url', e.target.value)}
                placeholder="https://maps.google.com/?q=…"
                maxLength={500}
              />
              <p className="text-xs text-gray-500 mt-1">
                Preferred "Open in Maps" link. Falls back to a search by address if blank.
              </p>
            </div>
            <div>
              <label className="text-sm font-medium">Address</label>
              <Input
                value={form.address}
                onChange={e => update('address', e.target.value)}
                placeholder="KG 123 St, Kigali"
                maxLength={300}
              />
            </div>
            <div>
              <label className="text-sm font-medium">WhatsApp number</label>
              <Input
                value={form.whatsapp}
                onChange={e => update('whatsapp', e.target.value)}
                placeholder="+250788000000"
                maxLength={40}
              />
            </div>
            <div className="md:col-span-2">
              <label className="text-sm font-medium">Website</label>
              <Input
                value={form.website_url}
                onChange={e => update('website_url', e.target.value)}
                placeholder="https://yoursite.rw"
                maxLength={300}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Payment Destination</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Where customers send mobile-money payment for cash-on-checkout
              orders. Master payment integration is still pending platform-wide;
              enabling this simply records the destination your storefront
              instructs customers to use. You can rely on the values shown — no
              automatic debits happen today.
            </p>
            <label className="flex items-center gap-2 text-sm font-medium">
              <input
                type="checkbox"
                checked={form.payment_enabled}
                onChange={e => update('payment_enabled', e.target.checked)}
              />
              Accept mobile-money payments — show a payment destination at checkout
            </label>
            {form.payment_enabled && (
              <div>
                <label className="text-sm font-medium">Payment phone number</label>
                <Input
                  type="tel"
                  value={form.payment_phone}
                  onChange={e => update('payment_phone', e.target.value)}
                  placeholder="+2507… (MoMo/airtel money number)"
                  maxLength={40}
                />
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Delivery & Tax</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-3">
            <p className="md:col-span-3 text-sm text-gray-500 dark:text-gray-400">
              Leave blank to use platform defaults. Values here are applied to every
              order — the storefront quote always matches the invoice.
            </p>
            <div>
              <label className="text-sm font-medium">Delivery fee</label>
              <Input
                type="number"
                min="0"
                step="0.01"
                value={form.delivery_fee}
                onChange={e => update('delivery_fee', e.target.value)}
                placeholder="Platform default"
              />
            </div>
            <div>
              <label className="text-sm font-medium">Free delivery above</label>
              <Input
                type="number"
                min="0"
                step="0.01"
                value={form.free_delivery_above}
                onChange={e => update('free_delivery_above', e.target.value)}
                placeholder="No threshold"
              />
            </div>
            <div>
              <label className="text-sm font-medium">Tax rate (%)</label>
              <Input
                type="number"
                min="0"
                max="50"
                step="0.01"
                value={form.tax_rate_pct}
                onChange={e => update('tax_rate_pct', e.target.value)}
                placeholder="Platform default"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Restocking</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              How IMBARAGA responds when a product drops to or below its reorder
              threshold.
            </p>
            <div className="grid gap-3 md:grid-cols-2">
              <label
                className={cn(
                  'flex cursor-pointer items-start gap-3 rounded-lg border p-4',
                  restockMode === 'auto'
                    ? 'border-emerald-400 bg-emerald-50 dark:bg-emerald-900/20'
                    : 'border-gray-200 dark:border-gray-700'
                )}
              >
                <input
                  type="radio"
                  name="restock_mode"
                  value="auto"
                  checked={restockMode === 'auto'}
                  onChange={() => setRestockMode('auto')}
                  className="mt-1"
                />
                <span>
                  <span className="block text-sm font-medium">
                    Auto — start restock on low stock
                  </span>
                  <span className="block text-xs text-gray-500 dark:text-gray-400">
                    When stock goes low, IMBARAGA automatically compares suppliers
                    and raises a purchase approval for you to review.
                  </span>
                </span>
              </label>
              <label
                className={cn(
                  'flex cursor-pointer items-start gap-3 rounded-lg border p-4',
                  restockMode === 'manual'
                    ? 'border-amber-400 bg-amber-50 dark:bg-amber-900/20'
                    : 'border-gray-200 dark:border-gray-700'
                )}
              >
                <input
                  type="radio"
                  name="restock_mode"
                  value="manual"
                  checked={restockMode === 'manual'}
                  onChange={() => setRestockMode('manual')}
                  className="mt-1"
                />
                <span>
                  <span className="block text-sm font-medium">
                    Manual — restock when I ask
                  </span>
                  <span className="block text-xs text-gray-500 dark:text-gray-400">
                    Low-stock alerts still appear, but you start any restock from
                    the stock keeper panel.
                  </span>
                </span>
              </label>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end">
          <Button type="submit" disabled={saving}>
            <Save className="h-4 w-4 mr-2" />
            {saving ? 'Saving…' : 'Save Changes'}
          </Button>
        </div>
      </form>
    </div>
  )
}
