'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import {
  getPlatformBusiness,
  setBusinessStatus,
  exportBusinessData,
  PlatformBusinessDetail,
} from '@/lib/api/platform'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Button } from '@/components/ui/Button'
import { Skeleton } from '@/components/ui/Skeleton'
import { ErrorState } from '@/components/ui/ErrorState'
import { useToast } from '@/components/ui/Toast'
import { Download, Pause, Play, Building2, Bot, FileText, Truck } from 'lucide-react'
import { cn } from '@/lib/utils'

const EXPORT_CATEGORIES: Array<{ key: string; label: string }> = [
  { key: 'ai_ops', label: 'AI Operations' },
  { key: 'operations', label: 'Operations' },
  { key: 'inventory', label: 'Inventory' },
  { key: 'suppliers', label: 'Suppliers' },
  { key: 'payments', label: 'Payments' },
  { key: 'customers', label: 'Customers' },
]

export default function PlatformBusinessDetailPage() {
  const params = useParams<{ id: string }>()
  const businessId = params.id
  const { toast } = useToast()
  const [data, setData] = useState<PlatformBusinessDetail | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [changingStatus, setChangingStatus] = useState(false)
  const [exporting, setExporting] = useState<string | null>(null)

  useEffect(() => {
    getPlatformBusiness(businessId).then(res => {
      if (res.success) setData(res.data)
      else setError(res.message)
    })
  }, [businessId])

  async function changeStatus(target: 'active' | 'suspended') {
    setChangingStatus(true)
    const res = await setBusinessStatus(businessId, target)
    setChangingStatus(false)
    if (!res.success) {
      toast({ title: res.message, variant: 'destructive' })
      return
    }
    toast({
      title: `Business ${target}${target === 'suspended' ? ' — operations stopped immediately' : ''}`,
      variant: target === 'active' ? 'success' : 'destructive',
    })
    const refreshed = await getPlatformBusiness(businessId)
    if (refreshed.success) setData(refreshed.data)
  }

  async function handleExport(category: string) {
    setExporting(category)
    const res = await exportBusinessData(businessId, category, 'csv')
    setExporting(null)
    if (!res.success) {
      toast({ title: res.message, variant: 'destructive' })
      return
    }
    const csv = typeof res.data === 'string' ? res.data : JSON.stringify(res.data)
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `imbaraga-${businessId.slice(0, 8)}-${category}.csv`
    a.click()
    URL.revokeObjectURL(url)
    toast({ title: `${category} export ready`, variant: 'success' })
  }

  if (error) return <ErrorState message={error} />
  if (!data) {
    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>
    )
  }

  const biz = data.business
  const invite = data.invites.find(i => !i.accepted_at && !i.revoked_at)
  const statusLabel =
    biz.status === 'active'
      ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
      : biz.status === 'suspended'
        ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
        : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">{biz.name}</h1>
            <span className={cn('inline-flex rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide', statusLabel)}>
              {biz.status}
            </span>
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {biz.slug} · {biz.industry || '—'} · {biz.country || '—'} · {biz.currency || '—'}
          </p>
        </div>
        {biz.status === 'pending' || biz.status === 'active' ? (
          <Button type="button" variant="danger" loading={changingStatus} onClick={() => changeStatus('suspended')}>
            <Pause className="h-4 w-4 mr-2" /> Suspend
          </Button>
        ) : (
          <Button type="button" variant="primary" loading={changingStatus} onClick={() => changeStatus('active')}>
            <Play className="h-4 w-4 mr-2" /> Re-activate
          </Button>
        )}
      </div>

      {biz.status === 'pending' && (
        <Card>
          <CardContent className="py-4 text-sm text-amber-700 dark:text-amber-300 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
            This business has not onboarded yet — the admin invite below is still
            open. It cannot operate until the first admin redeems it.
          </CardContent>
        </Card>
      )}

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <Card>
          <CardHeader><CardTitle className="text-sm text-gray-500 dark:text-gray-400">Products</CardTitle></CardHeader>
          <CardContent><p className="text-3xl font-bold">{data.metrics.products}</p></CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle className="text-sm text-gray-500 dark:text-gray-400">Orders</CardTitle></CardHeader>
          <CardContent>
            <p className="text-3xl font-bold">{data.metrics.orders_total}</p>
            <p className="mt-1 text-xs text-gray-500">
              {Object.entries(data.metrics.orders_by_status)
                .map(([s, n]) => `${s}: ${n}`)
                .join(' · ') || 'none'}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle className="text-sm text-gray-500 dark:text-gray-400">Pending approvals</CardTitle></CardHeader>
          <CardContent><p className="text-3xl font-bold">{data.metrics.pending_approvals}</p></CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
              <FileText className="h-4 w-4" /> Invoices
            </CardTitle>
          </CardHeader>
          <CardContent><p className="text-3xl font-bold">{data.metrics.invoices}</p></CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
              <Truck className="h-4 w-4" /> Suppliers
            </CardTitle>
          </CardHeader>
          <CardContent><p className="text-3xl font-bold">{data.metrics.suppliers}</p></CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle className="text-sm text-gray-500 dark:text-gray-400">Low stock items</CardTitle></CardHeader>
          <CardContent><p className="text-3xl font-bold">{data.metrics.low_stock_items}</p></CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <Bot className="h-5 w-5" /> AI operations
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4 text-sm">
          <div className="grid gap-2 sm:grid-cols-3">
            <p><span className="text-gray-500">Pending approvals:</span> <span className="font-medium">{data.metrics.pending_approvals}</span></p>
            <p><span className="text-gray-500">Tasks (all-time):</span> <span className="font-medium">{data.ai_activity.tasks_total}</span></p>
            <p><span className="text-gray-500">Agent actions (all-time):</span> <span className="font-medium">{data.ai_activity.actions_total}</span></p>
          </div>
          {data.ai_activity.tasks_total > 0 && (
            <p className="text-xs text-gray-500">
              Status: {Object.entries(data.ai_activity.tasks_by_status)
                .map(([s, n]) => `${s}: ${n}`)
                .join(' · ')}
            </p>
          )}
          {data.ai_activity.recent_tasks.length === 0 ? (
            <p className="text-gray-500">No AI operations recorded yet.</p>
          ) : (
            <ul className="divide-y divide-gray-200 dark:divide-gray-700">
              {data.ai_activity.recent_tasks.map(t => (
                <li key={t.id} className="py-2 flex items-center justify-between">
                  <span className="text-sm">{t.task_type}</span>
                  <span className="text-xs text-gray-500">
                    {t.status} · {t.started_at || t.scheduled_for ? new Date(t.started_at || t.scheduled_for || '').toLocaleString() : '—'}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-lg">
            <Building2 className="h-5 w-5" /> Onboarding status
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4 text-sm">
          <div className="grid gap-2 sm:grid-cols-2">
            <p><span className="text-gray-500">Owner:</span> {biz.owner_id ? 'Claimed' : 'Not yet — awaiting first admin'}</p>
            <p><span className="text-gray-500">Payment destination:</span> {biz.payment_enabled ? biz.payment_phone || 'configured' : 'Not enabled'}</p>
            <p><span className="text-gray-500">Storefront:</span> {biz.store_published ? 'Published' : 'Not published'}</p>
            <p><span className="text-gray-500">Created:</span> {new Date(biz.created_at).toLocaleString()}</p>
          </div>
          {invite ? (
            <div className="rounded-lg border border-gray-200 dark:border-gray-700 p-3 flex flex-wrap items-center justify-between gap-2">
              <p>
                Open invite: <span className="font-medium">{invite.role}</span>
                {invite.email ? ` for ${invite.email}` : ''} · expires {invite.expires_at ? new Date(invite.expires_at).toLocaleDateString() : '—'}
              </p>
              <a href={`mailto:${invite.email || ''}`} className="text-indigo-600 hover:underline dark:text-indigo-400">
                Email the invite holder
              </a>
            </div>
          ) : biz.status !== 'pending' ? (
            <p className="text-green-700 dark:text-green-400">
              No open invites. The business is onboarded.
            </p>
          ) : (
            <p className="text-amber-600">No valid invite found — create a new business to re-issue onboarding.</p>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Data exports</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
            Tenant-scoped exports as CSV — exact snapshots of what this business owns.
          </p>
          <div className="flex flex-wrap gap-2">
            {EXPORT_CATEGORIES.map(c => (
              <Button
                key={c.key}
                type="button"
                size="sm"
                variant="outline"
                loading={exporting === c.key}
                onClick={() => handleExport(c.key)}
              >
                <Download className="h-4 w-4 mr-1" /> {c.label}
              </Button>
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Members</CardTitle>
          </CardHeader>
          <CardContent>
            {data.members.length === 0 ? (
              <p className="text-sm text-gray-500">No members yet.</p>
            ) : (
              <ul className="divide-y divide-gray-200 dark:divide-gray-700">
                {data.members.map(m => (
                  <li key={m.id} className="py-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm">{m.full_name || m.id.slice(0, 8)}</span>
                      <span className="text-xs text-gray-500">{m.role} · {m.status}</span>
                    </div>
                    {m.email ? (
                      <a href={`mailto:${m.email}`} className="text-xs text-indigo-600 hover:underline dark:text-indigo-400">
                        {m.email}
                      </a>
                    ) : (
                      <p className="text-xs text-gray-400">No email on file</p>
                    )}
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Recent audit</CardTitle>
          </CardHeader>
          <CardContent>
            {data.recent_audit.length === 0 ? (
              <p className="text-sm text-gray-500">No audit events recorded.</p>
            ) : (
              <ul className="divide-y divide-gray-200 dark:divide-gray-700">
                {data.recent_audit.map((a, i) => (
                  <li key={i} className="py-2 text-sm">
                    <p className="font-medium">{a.action as string}</p>
                    <p className="text-xs text-gray-500">
                      {a.created_at ? new Date(a.created_at as string).toLocaleString() : ''}
                    </p>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}