'use client'

import { useState, useEffect, useCallback } from 'react'
import Image from 'next/image'
import {
  Download, RefreshCw, LogOut, Search, Package,
  ChevronDown, Check, X, ShoppingBag, Truck, Users, Euro, Sheet,
} from 'lucide-react'
import clsx from 'clsx'

interface Order {
  id: string
  orderNumber: string
  createdAt: string
  status: string
  product: string
  sizeTshirt?: string
  sizeSocks?: string
  nom: string
  cognoms: string
  email: string
  telefon: string
  shipping: string
  adreca?: string
  codiPostal?: string
  poblacio?: string
  provincia?: string
  baseAmount: number
  shippingAmount: number
  totalAmount: number
  notes?: string
}

const PRODUCT_SHORT: Record<string, string> = {
  samarreta: 'Samarreta',
  mitjons: 'Mitjons',
  pack: 'Pack S+M',
}

const STATUSES = ['PENDING', 'PAID', 'PREPARING', 'SHIPPED', 'DELIVERED', 'CANCELLED']

const STATUS_LABELS: Record<string, string> = {
  PENDING: 'Pendent',
  PAID: 'Pagat',
  PREPARING: 'Preparant',
  SHIPPED: 'Enviat',
  DELIVERED: 'Lliurat',
  CANCELLED: 'Cancel·lat',
}

function StatusBadge({ status }: { status: string }) {
  return (
    <span className={clsx('status-badge', `status-${status}`)}>
      {STATUS_LABELS[status] ?? status}
    </span>
  )
}

function StatsCard({ icon: Icon, label, value, color = 'text-teal' }: { icon: React.ElementType; label: string; value: string | number; color?: string }) {
  return (
    <div className="bg-dark-card border border-dark-border rounded-xl p-4 flex items-center gap-4">
      <div className={`${color} bg-dark rounded-lg p-2.5`}>
        <Icon size={20} />
      </div>
      <div>
        <div className="text-2xl font-black text-white">{value}</div>
        <div className="text-slate-500 text-xs">{label}</div>
      </div>
    </div>
  )
}

export default function AdminPage() {
  const [password, setPassword] = useState('')
  const [authed, setAuthed] = useState(false)
  const [authError, setAuthError] = useState('')
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(false)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('ALL')
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [updatingId, setUpdatingId] = useState<string | null>(null)
  const [syncing, setSyncing] = useState(false)
  const [syncMsg, setSyncMsg] = useState('')

  const fetchOrders = useCallback(async (pwd: string) => {
    setLoading(true)
    try {
      const res = await fetch('/api/orders', {
        headers: { 'x-admin-password': pwd },
      })
      if (!res.ok) throw new Error('No autoritzat')
      const data = await res.json()
      setOrders(data.orders)
    } catch {
      setAuthError('Contrasenya incorrecta')
      setAuthed(false)
    } finally {
      setLoading(false)
    }
  }, [])

  function handleLogin(e: React.FormEvent) {
    e.preventDefault()
    setAuthError('')
    localStorage.setItem('admin-pwd', password)
    setAuthed(true)
    fetchOrders(password)
  }

  useEffect(() => {
    const saved = localStorage.getItem('admin-pwd')
    if (saved) {
      setPassword(saved)
      setAuthed(true)
      fetchOrders(saved)
    }
  }, [fetchOrders])

  function handleLogout() {
    localStorage.removeItem('admin-pwd')
    setPassword('')
    setAuthed(false)
    setOrders([])
  }

  async function updateStatus(orderId: string, status: string) {
    setUpdatingId(orderId)
    try {
      await fetch('/api/orders', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'x-admin-password': password,
        },
        body: JSON.stringify({ id: orderId, status }),
      })
      setOrders((prev) =>
        prev.map((o) => (o.id === orderId ? { ...o, status } : o))
      )
    } finally {
      setUpdatingId(null)
    }
  }

  async function handleSyncSheets() {
    setSyncing(true)
    setSyncMsg('')
    try {
      const res = await fetch('/api/orders/sync-sheets', {
        method: 'POST',
        headers: { 'x-admin-password': password },
      })
      const data = await res.json()
      if (res.ok) setSyncMsg(`✓ ${data.synced} comandes sincronitzades`)
      else setSyncMsg('Error en sincronitzar')
    } catch {
      setSyncMsg('Error de connexió')
    } finally {
      setSyncing(false)
      setTimeout(() => setSyncMsg(''), 4000)
    }
  }

  function handleExport() {
    const url = `/api/orders?format=csv`
    const a = document.createElement('a')
    a.href = url
    a.setAttribute('data-password', password)
    // Use fetch to handle auth header
    fetch(url, { headers: { 'x-admin-password': password } })
      .then((r) => r.blob())
      .then((blob) => {
        const burl = URL.createObjectURL(blob)
        a.href = burl
        a.download = `comandes-cc2026-${new Date().toISOString().split('T')[0]}.csv`
        a.click()
        URL.revokeObjectURL(burl)
      })
  }

  // Filtered orders
  const filtered = orders.filter((o) => {
    if (statusFilter !== 'ALL' && o.status !== statusFilter) return false
    if (search) {
      const q = search.toLowerCase()
      return (
        o.orderNumber.toLowerCase().includes(q) ||
        o.nom.toLowerCase().includes(q) ||
        o.cognoms.toLowerCase().includes(q) ||
        o.email.toLowerCase().includes(q) ||
        o.telefon.includes(q)
      )
    }
    return true
  })

  // Stats
  const paid = orders.filter((o) => o.status !== 'PENDING' && o.status !== 'CANCELLED')
  const totalRevenue = paid.reduce((sum, o) => sum + o.totalAmount, 0)
  const countByProduct = {
    samarreta: orders.filter((o) => o.product === 'samarreta' && o.status !== 'CANCELLED').length,
    mitjons: orders.filter((o) => o.product === 'mitjons' && o.status !== 'CANCELLED').length,
    pack: orders.filter((o) => o.product === 'pack' && o.status !== 'CANCELLED').length,
  }

  // ─── Login ────────────────────────────────────────────────────────
  if (!authed) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4" style={{ background: '#070714' }}>
        <div className="w-full max-w-sm">
          <div className="text-center mb-8">
            <Image
              src="/assets/LOGO BLOD BROS SPORT GOTA  RODONA ALTA RES.jpg"
              alt="Blood Bros Sport"
              width={64}
              height={64}
              className="rounded-full mx-auto mb-4"
            />
            <h1 className="text-white font-black text-2xl">Panel d'administració</h1>
            <p className="text-slate-500 text-sm mt-1">Cursa de la Cirera 2026</p>
          </div>
          <form onSubmit={handleLogin} className="bg-dark-card border border-dark-border rounded-2xl p-6">
            <label className="form-label">Contrasenya</label>
            <input
              type="password"
              className="input-field mb-4"
              placeholder="Contrasenya d'administrador"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoFocus
            />
            {authError && (
              <p className="text-cherry text-sm mb-4 flex items-center gap-1">
                <X size={14} /> {authError}
              </p>
            )}
            <button
              type="submit"
              className="btn-pay"
              disabled={!password}
            >
              Entrar
            </button>
          </form>
        </div>
      </div>
    )
  }

  // ─── Admin panel ──────────────────────────────────────────────────
  return (
    <div className="min-h-screen" style={{ background: '#070714' }}>
      {/* Topbar */}
      <header className="border-b border-dark-border bg-dark/90 backdrop-blur-md sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Image
              src="/assets/LOGO BLOD BROS SPORT GOTA  RODONA ALTA RES.jpg"
              alt="Blood Bros Sport"
              width={36}
              height={36}
              className="rounded-full"
            />
            <div>
              <div className="text-white font-bold text-sm leading-tight">Admin Panel</div>
              <div className="text-slate-500 text-xs">Cursa de la Cirera 2026</div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => fetchOrders(password)}
              className="p-2 text-slate-400 hover:text-white transition-colors"
              title="Actualitzar"
            >
              <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
            </button>
            <button
              onClick={handleSyncSheets}
              disabled={syncing}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-green-500/10 border border-green-500/30 text-green-400 rounded-lg text-xs hover:bg-green-500/20 transition-colors disabled:opacity-50"
              title="Sincronitzar amb Google Sheets"
            >
              <Sheet size={14} className={syncing ? 'animate-spin' : ''} />
              {syncing ? 'Sincronitzant...' : syncMsg || 'Sheets'}
            </button>
            <button
              onClick={handleExport}
              className="flex items-center gap-1.5 px-3 py-1.5 bg-teal/10 border border-teal/30 text-teal rounded-lg text-xs hover:bg-teal/20 transition-colors"
            >
              <Download size={14} />
              CSV
            </button>
            <button
              onClick={handleLogout}
              className="p-2 text-slate-500 hover:text-white transition-colors"
              title="Sortir"
            >
              <LogOut size={16} />
            </button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 py-8">
        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          <StatsCard icon={Users} label="Comandes totals" value={orders.length} />
          <StatsCard icon={Euro} label="Ingressos" value={`${totalRevenue.toFixed(2).replace('.', ',')}€`} color="text-cherry" />
          <StatsCard icon={ShoppingBag} label="Samarretes + Packs" value={countByProduct.samarreta + countByProduct.pack} />
          <StatsCard icon={Package} label="Mitjons + Packs" value={countByProduct.mitjons + countByProduct.pack} />
        </div>

        {/* Product breakdown */}
        <div className="grid grid-cols-3 gap-3 mb-8">
          {Object.entries(PRODUCT_SHORT).map(([key, label]) => (
            <div key={key} className="bg-dark-card border border-dark-border rounded-xl p-3 text-center">
              <div className="text-2xl font-black text-white">{countByProduct[key as keyof typeof countByProduct]}</div>
              <div className="text-slate-500 text-xs">{label}</div>
            </div>
          ))}
        </div>

        {/* Status stats */}
        <div className="flex flex-wrap gap-2 mb-6">
          {['ALL', ...STATUSES].map((s) => {
            const count = s === 'ALL' ? orders.length : orders.filter((o) => o.status === s).length
            return (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className={clsx(
                  'flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold border transition-all',
                  statusFilter === s
                    ? 'bg-teal border-teal text-dark'
                    : 'bg-transparent border-dark-border text-slate-400 hover:border-dark-muted'
                )}
                style={statusFilter === s ? { color: '#000' } : undefined}
              >
                {s === 'ALL' ? 'Totes' : STATUS_LABELS[s]}
                <span className={clsx('text-[10px]', statusFilter === s ? 'opacity-70' : 'text-slate-600')}>
                  ({count})
                </span>
              </button>
            )
          })}
        </div>

        {/* Search */}
        <div className="relative mb-6">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
          <input
            type="text"
            className="input-field pl-9"
            placeholder="Cerca per nom, email, telèfon o número de comanda..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        {/* Orders table */}
        {loading ? (
          <div className="text-center py-16">
            <div className="w-10 h-10 border-4 border-teal border-t-transparent rounded-full animate-spin mx-auto" />
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-16 text-slate-600">
            {search || statusFilter !== 'ALL' ? 'Cap resultat per als filtres aplicats.' : 'No hi ha comandes encara.'}
          </div>
        ) : (
          <div className="space-y-2">
            {filtered.map((order) => (
              <div
                key={order.id}
                className="bg-dark-card border border-dark-border rounded-xl overflow-hidden"
              >
                {/* Row summary */}
                <button
                  onClick={() => setExpandedId(expandedId === order.id ? null : order.id)}
                  className="w-full text-left px-5 py-4 flex flex-wrap items-center gap-4 hover:bg-white/[0.02] transition-colors"
                >
                  <span className="text-teal font-black text-sm w-28 shrink-0">
                    {order.orderNumber}
                  </span>
                  <StatusBadge status={order.status} />
                  <span className="text-white text-sm font-medium flex-1 min-w-32">
                    {order.nom} {order.cognoms}
                  </span>
                  <span className="text-slate-500 text-sm hidden sm:block">
                    {PRODUCT_SHORT[order.product] ?? order.product}
                    {order.sizeTshirt && ` · S${order.sizeTshirt}`}
                    {order.sizeSocks && ` · M${order.sizeSocks}`}
                  </span>
                  <span className="text-white font-bold text-sm ml-auto">
                    {order.totalAmount.toFixed(2).replace('.', ',')}€
                  </span>
                  <ChevronDown
                    size={16}
                    className={clsx('text-slate-500 shrink-0 transition-transform', expandedId === order.id && 'rotate-180')}
                  />
                </button>

                {/* Expanded detail */}
                {expandedId === order.id && (
                  <div className="border-t border-dark-border px-5 py-4 grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    {/* Contact */}
                    <div>
                      <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Client</p>
                      <p className="text-white text-sm font-semibold">{order.nom} {order.cognoms}</p>
                      <p className="text-slate-400 text-sm">{order.email}</p>
                      <p className="text-slate-400 text-sm">{order.telefon}</p>
                      <p className="text-slate-500 text-xs mt-1">
                        {new Date(order.createdAt).toLocaleDateString('ca-ES', {
                          day: '2-digit', month: '2-digit', year: 'numeric',
                          hour: '2-digit', minute: '2-digit',
                        })}
                      </p>
                    </div>

                    {/* Shipping */}
                    <div>
                      <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Lliurament</p>
                      <p className="text-white text-sm font-semibold">
                        {order.shipping === 'correos' ? 'Correos Express' : 'Recollida Corbins/Lleida'}
                      </p>
                      {order.shipping === 'correos' && order.adreca && (
                        <p className="text-slate-400 text-sm mt-1">
                          {order.adreca}<br />
                          {order.codiPostal} {order.poblacio}<br />
                          {order.provincia}
                        </p>
                      )}
                    </div>

                    {/* Status update */}
                    <div>
                      <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Canviar estat</p>
                      <div className="flex flex-wrap gap-1.5">
                        {STATUSES.map((s) => (
                          <button
                            key={s}
                            onClick={() => updateStatus(order.id, s)}
                            disabled={updatingId === order.id || order.status === s}
                            className={clsx(
                              'px-2.5 py-1 rounded-lg text-xs font-semibold border transition-all',
                              order.status === s
                                ? 'bg-teal/20 border-teal text-teal'
                                : 'bg-transparent border-dark-border text-slate-400 hover:border-dark-muted hover:text-white',
                              updatingId === order.id && 'opacity-50 cursor-not-allowed'
                            )}
                          >
                            {order.status === s && <Check size={10} className="inline mr-1" />}
                            {STATUS_LABELS[s]}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        <p className="text-center text-slate-700 text-xs mt-8">
          {filtered.length} comanda{filtered.length !== 1 ? 'es' : ''} mostrade{filtered.length !== 1 ? 's' : ''}
          {orders.length !== filtered.length && ` de ${orders.length} totals`}
        </p>
      </div>
    </div>
  )
}
