'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import {
  listPlatformBusinesses,
  createPlatformBusiness,
  CreateBusinessInput,
  PlatformBusiness,
} from '@/lib/api/platform'
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 { Building2, Plus, Copy, Mail } from 'lucide-react'
import { cn } from '@/lib/utils'

type StatusFilter = 'all' | 'pending' | 'active' | 'suspended'

export default function PlatformBusinessesPage() {
  const { toast } = useToast()
  const [filter, setFilter] = useState<StatusFilter>('all')
  const [businesses, setBusinesses] = useState<PlatformBusiness[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [showCreate, setShowCreate] = useState(false)
  const [creating, setCreating] = useState(false)
  const [created, setCreated] = useState<{ name: string; invite_url: string } | null>(null)
  const [form, setForm] = useState<CreateBusinessInput>({
    name: '',
    industry: '',
    country: '',
    currency: 'RWF',
    admin_email: '',
    admin_full_name: '',
  })

  async function load() {
    setLoading(true)
    const res = await listPlatformBusinesses(filter === 'all' ? undefined : filter)
    if (res.success) {
      setBusinesses(res.data.businesses)
      setError(null)
    } else {
      setError(res.message)
    }
    setLoading(false)
  }

  useEffect(() => {
    load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filter])

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault()
    setCreating(true)
    setCreated(null)
    const res = await createPlatformBusiness(form)
    setCreating(false)
    if (!res.success) {
      toast({ title: res.message, variant: 'destructive' })
      return
    }
    const d = res.data
    setCreated({ name: d.name, invite_url: d.onboarding.invite_url })
    setShowCreate(false)
    setForm({ name: '', industry: '', country: '', currency: 'RWF', admin_email: '', admin_full_name: '' })
    toast({
      title: 'Business created',
      description: `${d.name} is pending — the admin invite is ready to share.`,
      variant: 'success',
    })
    load()
  }

  async function copyInvite() {
    if (!created) return
    try {
      await navigator.clipboard.writeText(created.invite_url)
      toast({ title: 'Invite link copied', variant: 'success' })
    } catch {
      toast({ title: 'Copy failed — copy manually', variant: 'destructive' })
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Businesses</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Create business workspaces and control their activation.
          </p>
        </div>
        <Button type="button" onClick={() => setShowCreate(s => !s)}>
          <Plus className="h-4 w-4 mr-2" /> New Business
        </Button>
      </div>

      {showCreate && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <Building2 className="h-5 w-5" /> Onboard a business
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleCreate} className="grid gap-4 md:grid-cols-2">
              <div className="md:col-span-2">
                <label className="text-sm font-medium">Business name *</label>
                <Input
                  value={form.name}
                  onChange={e => setForm({ ...form, name: e.target.value })}
                  placeholder="Kigali Audio Source"
                  required
                  maxLength={160}
                />
              </div>
              <div>
                <label className="text-sm font-medium">Industry</label>
                <Input
                  value={form.industry ?? ''}
                  onChange={e => setForm({ ...form, industry: e.target.value })}
                  placeholder="Consumer electronics"
                  maxLength={160}
                />
              </div>
              <div>
                <label className="text-sm font-medium">Country</label>
                <Input
                  value={form.country ?? ''}
                  onChange={e => setForm({ ...form, country: e.target.value })}
                  placeholder="Rwanda"
                  maxLength={120}
                />
              </div>
              <div>
                <label className="text-sm font-medium">Currency</label>
                <Input
                  value={form.currency ?? ''}
                  onChange={e => setForm({ ...form, currency: e.target.value })}
                  placeholder="RWF"
                  maxLength={8}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm font-medium">
                  Admin email (owner of the first invite) *
                </label>
                <Input
                  type="email"
                  value={form.admin_email}
                  onChange={e => setForm({ ...form, admin_email: e.target.value })}
                  placeholder="owner@company.rw"
                  required
                  maxLength={160}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Whoever redeems this invite becomes the business owner, activates the
                  business, and receives the admin role.
                </p>
              </div>
              <div className="md:col-span-2">
                <label className="text-sm font-medium">Admin full name</label>
                <Input
                  value={form.admin_full_name ?? ''}
                  onChange={e => setForm({ ...form, admin_full_name: e.target.value })}
                  placeholder="Jane Doe"
                  maxLength={160}
                />
              </div>
              <div className="md:col-span-2 flex justify-end gap-2">
                <Button type="button" variant="outline" onClick={() => setShowCreate(false)}>
                  Cancel
                </Button>
                <Button type="submit" loading={creating}>
                  {creating ? 'Creating…' : 'Create Business & Invite'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}

      {created && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <Mail className="h-5 w-5" /> Onboarding invite for {created.name}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Share this link with the admin you named. Until they redeem it the business
              stays <span className="font-medium text-amber-600">pending</span> and cannot
              operate.
            </p>
            <div className="flex flex-wrap items-center gap-2">
              <code className="rounded bg-gray-100 dark:bg-gray-800 px-3 py-2 text-sm break-all">
                {created.invite_url}
              </code>
              <Button type="button" size="sm" variant="outline" onClick={copyInvite}>
                <Copy className="h-4 w-4 mr-1" /> Copy
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      <div className="flex flex-wrap gap-2" role="tablist" aria-label="Business status filter">
        {(['all', 'pending', 'active', 'suspended'] as StatusFilter[]).map(s => (
          <button
            key={s}
            role="tab"
            aria-selected={filter === s}
            onClick={() => setFilter(s)}
            className={cn(
              'rounded-full px-4 py-1.5 text-sm font-medium capitalize transition-colors',
              filter === s
                ? 'bg-indigo-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300'
            )}
          >
            {s}
          </button>
        ))}
      </div>

      {error && <ErrorState message={error} />}

      {loading ? (
        <Skeleton className="h-56 w-full" />
      ) : businesses.length === 0 ? (
        <Card>
          <CardContent className="py-10 text-center text-sm text-gray-500">
            No businesses match this filter.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <ul className="divide-y divide-gray-200 dark:divide-gray-700">
              {businesses.map(b => (
                <li key={b.id}>
                  <Link href={`/platform/businesses/${b.id}`} className="flex items-center justify-between gap-4 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800">
                    <div className="min-w-0">
                      <p className="font-medium text-gray-900 dark:text-white truncate">{b.name}</p>
                      <p className="text-xs text-gray-500 truncate">
                        {b.slug} · {b.industry || '—'} · {b.currency || '—'}
                      </p>
                    </div>
                    <div className="flex shrink-0 items-center gap-3">
                      {b.payment_enabled && (
                        <span className="text-xs text-emerald-600 dark:text-emerald-400">
                          payments enabled
                        </span>
                      )}
                      {b.store_published && (
                        <span className="text-xs text-blue-600 dark:text-blue-400">storefront live</span>
                      )}
                      <span
                        className={cn(
                          'inline-flex rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide',
                          b.status === 'active'
                            ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
                            : b.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'
                        )}
                      >
                        {b.status}
                      </span>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      )}
    </div>
  )
}