import { useState } from 'react'
import {
  ArchiveRestore,
  Eye,
  MoreHorizontal,
  RotateCcw,
  Trash2,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Area,
  AreaChart,
  CartesianGrid,
  ChartContainer,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
  Legend,
  XAxis,
  YAxis,
} from '@/components/ui/chart'
import {
  AdminActionDialog,
  AdminRowActionsMenu,
  BatchOperationsToolbar,
  EntityDetailSheet,
  ResourcePreview,
  SelectableList,
  StatusBadge,
  formatBoolean,
  formatDateTime,
  formatEnumLabel,
} from '@/components/admin'
import { ConfigDrawer } from '@/components/config-drawer'
import { Header } from '@/components/layout/header'
import { Main } from '@/components/layout/main'
import { ProfileDropdown } from '@/components/profile-dropdown'
import { Search } from '@/components/search'
import { ThemeSwitch } from '@/components/theme-switch'

const chartData = [
  { month: 'Jan', desktop: 186, mobile: 80 },
  { month: 'Feb', desktop: 305, mobile: 200 },
  { month: 'Mar', desktop: 237, mobile: 120 },
  { month: 'Apr', desktop: 73, mobile: 190 },
  { month: 'May', desktop: 209, mobile: 130 },
  { month: 'Jun', desktop: 214, mobile: 140 },
]

const selectableItems = [
  {
    id: 'analytics',
    title: 'Analytics',
    subtitle: 'View reporting dashboards',
  },
  { id: 'billing', title: 'Billing', subtitle: 'Manage invoices and plans' },
  { id: 'security', title: 'Security', subtitle: 'Configure access controls' },
]

const exampleUpdatedAt = '2026-01-15T09:30:00'

export function Components() {
  const [actionOpen, setActionOpen] = useState(false)
  const [detailOpen, setDetailOpen] = useState(false)
  const [selectedIds, setSelectedIds] = useState<(string | number)[]>([
    'analytics',
    'security',
  ])

  function toggleItem(id: string | number) {
    setSelectedIds((current) =>
      current.includes(id)
        ? current.filter((item) => item !== id)
        : [...current, id]
    )
  }

  return (
    <>
      <Header>
        <div className='ms-auto flex items-center space-x-4'>
          <Search />
          <ThemeSwitch />
          <ConfigDrawer />
          <ProfileDropdown />
        </div>
      </Header>

      <Main>
        <div className='admin-toolbar mb-6'>
          <div>
            <h1 className='text-2xl font-bold tracking-tight'>Components</h1>
            <p className='text-muted-foreground'>
              Reusable admin patterns and styling tokens ready for product
              screens.
            </p>
          </div>
          <div className='admin-toolbar-group'>
            <Button variant='outline' onClick={() => setDetailOpen(true)}>
              <Eye className='size-4' />
              View detail
            </Button>
            <Button onClick={() => setActionOpen(true)}>
              <MoreHorizontal className='size-4' />
              Open action
            </Button>
          </div>
        </div>

        <div className='grid gap-4 lg:grid-cols-3'>
          <Card className='lg:col-span-2'>
            <CardHeader>
              <CardTitle>Status Tokens</CardTitle>
              <CardDescription>
                Semantic tones pulled into the theme for reusable admin states.
              </CardDescription>
            </CardHeader>
            <CardContent className='flex flex-wrap gap-2'>
              <StatusBadge tone='success' label='Published' />
              <StatusBadge tone='warning' label='Pending review' />
              <StatusBadge tone='info' label='Processing' />
              <StatusBadge tone='danger' label='Blocked' />
              <StatusBadge tone='neutral' label='Archived' />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Readable Fields</CardTitle>
              <CardDescription>
                Small helpers for readable entity values.
              </CardDescription>
            </CardHeader>
            <CardContent className='space-y-3 text-sm'>
              <div className='flex justify-between gap-4'>
                <span className='text-muted-foreground'>Status</span>
                <span className='font-medium'>
                  {formatEnumLabel('active_user')}
                </span>
              </div>
              <div className='flex justify-between gap-4'>
                <span className='text-muted-foreground'>Enabled</span>
                <span className='font-medium'>{formatBoolean(true)}</span>
              </div>
              <div className='flex justify-between gap-4'>
                <span className='text-muted-foreground'>Updated</span>
                <span className='font-medium'>
                  {formatDateTime(exampleUpdatedAt)}
                </span>
              </div>
            </CardContent>
          </Card>
        </div>

        <div className='mt-4 grid gap-4 lg:grid-cols-2'>
          <Card>
            <CardHeader>
              <CardTitle>Batch Toolbar</CardTitle>
              <CardDescription>
                A floating bulk action surface for table selections.
              </CardDescription>
            </CardHeader>
            <CardContent className='space-y-4'>
              <BatchOperationsToolbar
                selectedCount={selectedIds.length}
                totalCount={selectableItems.length}
                onSelectAll={() =>
                  setSelectedIds(selectableItems.map((item) => item.id))
                }
                onClearSelection={() => setSelectedIds([])}
                actions={[
                  {
                    id: 'restore',
                    label: 'Restore',
                    tone: 'success',
                    confirmTitle: 'Restore selected records?',
                    confirmDescription:
                      'This demonstrates a non-destructive bulk action pattern.',
                    confirmLabel: 'Restore',
                  },
                  {
                    id: 'delete',
                    label: 'Delete',
                    destructive: true,
                    tone: 'danger',
                    confirmTitle: 'Delete selected records?',
                    confirmDescription:
                      'Destructive actions require a short note before confirmation.',
                    confirmLabel: 'Delete',
                  },
                ]}
                onAction={() => undefined}
              />
              <SelectableList
                items={selectableItems}
                selectedIds={selectedIds}
                onToggle={toggleItem}
                getId={(item) => item.id}
                getTitle={(item) => item.title}
                getSubtitle={(item) => item.subtitle}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <div className='flex items-start justify-between gap-4'>
                <div>
                  <CardTitle>Row Actions</CardTitle>
                  <CardDescription>
                    Compact table actions with loading and destructive states.
                  </CardDescription>
                </div>
                <AdminRowActionsMenu
                  label='Record actions'
                  actions={[
                    {
                      label: 'View',
                      icon: Eye,
                      onSelect: () => setDetailOpen(true),
                    },
                    { label: 'Restore', icon: ArchiveRestore },
                    {
                      label: 'Reset',
                      icon: RotateCcw,
                      separatorBefore: true,
                    },
                    { label: 'Delete', icon: Trash2, destructive: true },
                  ]}
                />
              </div>
            </CardHeader>
            <CardContent>
              <div className='admin-table-shell'>
                <div className='grid grid-cols-3 border-b bg-muted/40 px-4 py-2 text-xs font-medium text-muted-foreground'>
                  <span>Name</span>
                  <span>Status</span>
                  <span className='text-end'>Score</span>
                </div>
                {[
                  ['Acme Analytics', 'Active', '98'],
                  ['Billing Portal', 'Pending', '76'],
                  ['Support Queue', 'Archived', '54'],
                ].map(([name, status, score]) => (
                  <div
                    key={name}
                    className='admin-table-row grid grid-cols-3 items-center px-4 py-3 text-sm'
                  >
                    <span className='font-medium'>{name}</span>
                    <span>{status}</span>
                    <span className='text-end tabular-nums'>{score}</span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        <Card className='mt-4'>
          <CardHeader>
            <CardTitle>Chart Primitive</CardTitle>
            <CardDescription>
              A safe Recharts wrapper with themed tooltip and legend styles.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer
              className='h-[280px] w-full'
              config={{
                desktop: { label: 'Desktop', color: 'var(--chart-1)' },
                mobile: { label: 'Mobile', color: 'var(--chart-2)' },
              }}
            >
              <AreaChart data={chartData} margin={{ left: 12, right: 12 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey='month' tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} width={32} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Legend content={<ChartLegendContent />} />
                <Area
                  dataKey='desktop'
                  type='natural'
                  fill='var(--color-desktop)'
                  fillOpacity={0.28}
                  stroke='var(--color-desktop)'
                />
                <Area
                  dataKey='mobile'
                  type='natural'
                  fill='var(--color-mobile)'
                  fillOpacity={0.18}
                  stroke='var(--color-mobile)'
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </Main>

      <AdminActionDialog
        open={actionOpen}
        onOpenChange={setActionOpen}
        title='Run template action?'
        description='Use this dialog for confirmable admin actions that need tone, icon, loading, and optional custom content.'
        confirmLabel='Run action'
        tone='info'
        onConfirm={() => setActionOpen(false)}
      />

      <EntityDetailSheet
        open={detailOpen}
        onOpenChange={setDetailOpen}
        title='Acme Analytics'
        description='A reusable detail sheet for records, approvals, profiles, or any entity-like data.'
        status={{ label: 'Active', tone: 'success' }}
        meta='ID: demo-001'
        sections={[
          {
            title: 'Overview',
            fields: [
              { label: 'Owner', value: 'Jane Cooper' },
              { label: 'Plan', value: 'Enterprise' },
              { label: 'Region', value: 'North America' },
              { label: 'Created', value: formatDateTime(exampleUpdatedAt) },
            ],
          },
          {
            title: 'Resource',
            description:
              'Media previews accept plain URLs or a custom resolver.',
            content: (
              <ResourcePreview
                value='https://images.unsplash.com/photo-1497366754035-f200968a6e72?w=800'
                type='image'
              />
            ),
          },
        ]}
        actions={[
          {
            label: 'Reset',
            icon: RotateCcw,
            onClick: () => setDetailOpen(false),
          },
          {
            label: 'Archive',
            icon: Trash2,
            variant: 'destructive',
            onClick: () => setDetailOpen(false),
          },
        ]}
      />
    </>
  )
}
