import type { Meta, StoryObj } from '@storybook/react';
import { Activity, Copy, MoreHorizontal, Plus, RefreshCw, ShieldCheck, Trash2 } from 'lucide-react';
import { ActionMenu } from './ActionMenu.js';
import { AlertBanner } from './AlertBanner.js';
import { Badge } from './Badge.js';
import { Button } from './Button.js';
import {
  DataTable,
  DataTableBody,
  DataTableCell,
  DataTableHead,
  DataTableHeader,
  DataTableRow,
} from './DataTable.js';
import { EmptyState } from './EmptyState.js';
import { EntityCard } from './EntityCard.js';
import { FieldGrid } from './FieldGrid.js';
import { FilterBar } from './FilterBar.js';
import { FormSection } from './FormSection.js';
import { Input } from './Input.js';
import { MetricCard } from './MetricCard.js';
import { PageHeader } from './PageHeader.js';
import { Panel, PanelBody, PanelDescription, PanelHeader, PanelTitle } from './Panel.js';
import { Section } from './Section.js';
import { Select } from './Select.js';
import { Skeleton, TableSkeleton } from './Skeleton.js';
import { StatusBadge } from './StatusBadge.js';
import { Textarea } from './Textarea.js';
import { Toolbar } from './Toolbar.js';

const meta: Meta = {
  title: 'Examples/Operational Preview',
  parameters: {
    layout: 'fullscreen',
  },
};

export default meta;
type Story = StoryObj;

export const LaunchReadyConsole: Story = {
  render: () => (
    <main className="min-h-screen bg-[var(--bl-bg-canvas)] p-6 text-[var(--bl-text-primary)]">
      <div className="mx-auto grid max-w-7xl gap-6">
        <PageHeader
          eyebrow="ByteLyst platform preview"
          title="Operational trading console"
          description="A realistic composition for validating shared tokens, primitives, density, states, and responsive behavior before product teams adopt the system."
          metadata={
            <>
              <Badge variant="success" dot>
                Local packages
              </Badge>
              <Badge variant="info" dot>
                Strict audit clean
              </Badge>
            </>
          }
          actions={
            <>
              <Button variant="secondary" size="sm">
                <RefreshCw className="h-4 w-4" aria-hidden="true" />
                Refresh
              </Button>
              <Button size="sm">
                <Plus className="h-4 w-4" aria-hidden="true" />
                New setup
              </Button>
            </>
          }
        />

        <AlertBanner tone="warning" title="Production bar">
          Every route should look deliberate in populated, loading, empty, error, disabled, and
          destructive-action states.
        </AlertBanner>

        <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <MetricCard label="Portfolio value" value="$128,420" trend="+4.8% today" tone="success" />
          <MetricCard label="Open setups" value="18" trend="3 need review" tone="warning" />
          <MetricCard
            label="Execution state"
            value="Paper"
            trend="Live trading locked"
            tone="info"
          />
          <MetricCard label="Risk budget" value="62%" trend="Within limits" tone="success" />
        </section>

        <FilterBar
          searchValue="BTC"
          onSearchChange={() => undefined}
          searchPlaceholder="Search symbol, setup, or owner..."
          chips={
            <>
              <Badge variant="accent">Crypto</Badge>
              <Badge variant="neutral">Active only</Badge>
            </>
          }
          filters={
            <>
              <Select
                aria-label="Status"
                value="active"
                options={[
                  { value: 'active', label: 'Active' },
                  { value: 'waiting', label: 'Waiting' },
                  { value: 'closed', label: 'Closed' },
                ]}
              />
              <Select
                aria-label="Strategy"
                value="all"
                options={[
                  { value: 'all', label: 'All strategies' },
                  { value: 'simple', label: 'Simple auto' },
                  { value: 'manual', label: 'Manual' },
                ]}
              />
            </>
          }
          actions={
            <Button variant="subtle" size="sm">
              Export
            </Button>
          }
          onReset={() => undefined}
        />

        <div className="grid gap-6 xl:grid-cols-[1fr_360px]">
          <Section
            title="Active setups"
            description="Dense data surfaces should scan cleanly and recover gracefully from loading, empty, and error states."
            actions={
              <Toolbar>
                <Button variant="ghost" size="sm">
                  All
                </Button>
                <Button variant="subtle" size="sm">
                  Needs attention
                </Button>
                <Button variant="ghost" size="sm">
                  Closed
                </Button>
              </Toolbar>
            }
          >
            <Panel>
              <PanelHeader>
                <div>
                  <PanelTitle>Runtime order state</PanelTitle>
                  <PanelDescription>Responsive table with compact row actions.</PanelDescription>
                </div>
                <StatusBadge tone="success" dot>
                  Synced
                </StatusBadge>
              </PanelHeader>
              <PanelBody>
                <DataTable>
                  <DataTableHeader>
                    <DataTableRow>
                      <DataTableHead>Symbol</DataTableHead>
                      <DataTableHead>State</DataTableHead>
                      <DataTableHead>Budget</DataTableHead>
                      <DataTableHead>P/L</DataTableHead>
                      <DataTableHead>Action</DataTableHead>
                    </DataTableRow>
                  </DataTableHeader>
                  <DataTableBody>
                    {[
                      ['BTC/USD', 'Waiting', '$120.00', '+2.4%'],
                      ['ETH/USD', 'Armed', '$90.00', '-0.7%'],
                      ['AAPL', 'Review', '$250.00', '+0.8%'],
                    ].map(([symbol, state, budget, pnl]) => (
                      <DataTableRow key={symbol}>
                        <DataTableCell className="font-semibold">{symbol}</DataTableCell>
                        <DataTableCell>
                          <StatusBadge tone={state === 'Review' ? 'warning' : 'info'} dot>
                            {state}
                          </StatusBadge>
                        </DataTableCell>
                        <DataTableCell>{budget}</DataTableCell>
                        <DataTableCell>{pnl}</DataTableCell>
                        <DataTableCell>
                          <ActionMenu
                            items={[
                              {
                                id: 'copy',
                                label: 'Clone setup',
                                icon: <Copy className="h-4 w-4" />,
                                onSelect: () => undefined,
                              },
                              {
                                id: 'archive',
                                label: 'Archive',
                                icon: <MoreHorizontal className="h-4 w-4" />,
                                onSelect: () => undefined,
                              },
                              {
                                id: 'delete',
                                label: 'Delete',
                                icon: <Trash2 className="h-4 w-4" />,
                                destructive: true,
                                onSelect: () => undefined,
                              },
                            ]}
                          />
                        </DataTableCell>
                      </DataTableRow>
                    ))}
                  </DataTableBody>
                </DataTable>
              </PanelBody>
            </Panel>

            <div className="grid gap-4 lg:grid-cols-2">
              <EntityCard
                eyebrow="Strategy"
                title="Breakout confirmation"
                subtitle="BTC/USD paper setup with managed profit exit."
                status={<StatusBadge tone="success">Ready</StatusBadge>}
                metadata={
                  <>
                    <Badge>Budget $120</Badge>
                    <Badge variant="info">Short term</Badge>
                  </>
                }
                actions={
                  <Button variant="secondary" size="sm">
                    Open
                  </Button>
                }
                footer={
                  <span className="text-sm text-[var(--bl-text-secondary)]">
                    Updated 4 minutes ago
                  </span>
                }
              />
              <EmptyState
                title="No critical alerts"
                description="This compact empty state keeps low-volume surfaces feeling complete."
                icon={<ShieldCheck className="h-10 w-10" />}
              />
            </div>
          </Section>

          <aside className="grid gap-6">
            <FormSection
              title="Plan builder"
              description="Forms use consistent spacing, labels, hints, and review sections."
            >
              <FieldGrid columns={1}>
                <Input label="Symbol" value="BTC/USD" readOnly />
                <Select
                  label="Setup type"
                  value="dip"
                  options={[
                    { value: 'dip', label: 'Buy the dip' },
                    { value: 'breakout', label: 'Breakout' },
                  ]}
                />
                <Textarea label="Notes" placeholder="Optional context" />
              </FieldGrid>
              <Button>Save setup</Button>
            </FormSection>

            <Panel>
              <PanelHeader>
                <div>
                  <PanelTitle>Loading shape</PanelTitle>
                  <PanelDescription>Skeletons should match final layout.</PanelDescription>
                </div>
              </PanelHeader>
              <PanelBody>
                <div className="flex items-center gap-3">
                  <Skeleton shape="circle" />
                  <div className="grid flex-1 gap-2">
                    <Skeleton shape="text" />
                    <Skeleton shape="text" className="w-2/3" />
                  </div>
                </div>
                <TableSkeleton rows={3} />
              </PanelBody>
            </Panel>

            <Panel>
              <PanelHeader>
                <div>
                  <PanelTitle>System health</PanelTitle>
                  <PanelDescription>State should be visible without reading logs.</PanelDescription>
                </div>
                <Activity className="h-5 w-5 text-[var(--bl-success)]" aria-hidden="true" />
              </PanelHeader>
              <PanelBody>
                <AlertBanner tone="success">
                  All shared primitives render from common platform.
                </AlertBanner>
              </PanelBody>
            </Panel>
          </aside>
        </div>
      </div>
    </main>
  ),
};

export const LaunchStateMatrix: Story = {
  render: () => (
    <main className="min-h-screen bg-[var(--bl-bg-canvas)] p-6 text-[var(--bl-text-primary)]">
      <div className="mx-auto grid max-w-6xl gap-6">
        <PageHeader
          eyebrow="Launch readiness"
          title="State matrix"
          description="Shared product states for checking loading, empty, warning, error, disabled, confirmation, and dense data behavior before a route ships."
          metadata={
            <>
              <Badge variant="info" dot>
                Reusable
              </Badge>
              <Badge variant="success" dot>
                Accessible states
              </Badge>
            </>
          }
        />

        <div className="grid gap-4 lg:grid-cols-2">
          <Panel>
            <PanelHeader>
              <div>
                <PanelTitle>Loading</PanelTitle>
                <PanelDescription>Skeletons match the final rhythm and density.</PanelDescription>
              </div>
              <StatusBadge tone="info" dot>
                Fetching
              </StatusBadge>
            </PanelHeader>
            <PanelBody>
              <div className="grid gap-3">
                <div className="flex items-center gap-3">
                  <Skeleton shape="circle" />
                  <div className="grid flex-1 gap-2">
                    <Skeleton shape="text" className="w-2/3" />
                    <Skeleton shape="text" className="w-1/2" />
                  </div>
                </div>
                <TableSkeleton rows={4} />
              </div>
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader>
              <div>
                <PanelTitle>Empty</PanelTitle>
                <PanelDescription>Empty states provide a clear next action.</PanelDescription>
              </div>
            </PanelHeader>
            <PanelBody>
              <EmptyState
                title="No setups need review"
                description="When work is complete, the surface should still feel intentional."
                icon={<ShieldCheck className="h-10 w-10" />}
                action={
                  <Button size="sm" variant="secondary">
                    Create setup
                  </Button>
                }
              />
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader>
              <div>
                <PanelTitle>Alert stack</PanelTitle>
                <PanelDescription>Warnings and errors use consistent semantics.</PanelDescription>
              </div>
            </PanelHeader>
            <PanelBody>
              <div className="grid gap-3">
                <AlertBanner tone="warning" title="Data freshness degraded">
                  Market data is delayed. Show the user what changed and whether action is safe.
                </AlertBanner>
                <AlertBanner tone="error" title="Execution blocked">
                  Destructive or risky actions require a clear reason and recovery path.
                </AlertBanner>
              </div>
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader>
              <div>
                <PanelTitle>Forms and disabled states</PanelTitle>
                <PanelDescription>Controls remain readable when unavailable.</PanelDescription>
              </div>
              <Badge variant="neutral">Read-only</Badge>
            </PanelHeader>
            <PanelBody>
              <FormSection
                title="Risk limits"
                description="Disabled controls explain state nearby."
              >
                <FieldGrid columns={2}>
                  <Input label="Max daily loss" value="$250" readOnly />
                  <Select
                    label="Execution mode"
                    value="paper"
                    disabled
                    options={[
                      { value: 'paper', label: 'Paper trading' },
                      { value: 'live', label: 'Live trading' },
                    ]}
                  />
                </FieldGrid>
                <AlertBanner tone="info">
                  Live execution is locked until admin approval is complete.
                </AlertBanner>
              </FormSection>
            </PanelBody>
          </Panel>

          <Panel className="lg:col-span-2">
            <PanelHeader>
              <div>
                <PanelTitle>Destructive confirmation context</PanelTitle>
                <PanelDescription>
                  Danger actions should be visually distinct and isolated.
                </PanelDescription>
              </div>
              <Button variant="destructive" size="sm">
                <Trash2 className="h-4 w-4" aria-hidden="true" />
                Delete setup
              </Button>
            </PanelHeader>
            <PanelBody>
              <DataTable>
                <DataTableHeader>
                  <DataTableRow>
                    <DataTableHead>Resource</DataTableHead>
                    <DataTableHead>State</DataTableHead>
                    <DataTableHead>Owner</DataTableHead>
                    <DataTableHead>Impact</DataTableHead>
                  </DataTableRow>
                </DataTableHeader>
                <DataTableBody>
                  <DataTableRow>
                    <DataTableCell className="font-semibold">BTC managed setup</DataTableCell>
                    <DataTableCell>
                      <StatusBadge tone="warning" dot>
                        Armed
                      </StatusBadge>
                    </DataTableCell>
                    <DataTableCell>Trading operations</DataTableCell>
                    <DataTableCell>Open automation will be cancelled</DataTableCell>
                  </DataTableRow>
                  <DataTableRow>
                    <DataTableCell className="font-semibold">Audit trail</DataTableCell>
                    <DataTableCell>
                      <StatusBadge tone="success" dot>
                        Retained
                      </StatusBadge>
                    </DataTableCell>
                    <DataTableCell>Platform</DataTableCell>
                    <DataTableCell>Historical events remain available</DataTableCell>
                  </DataTableRow>
                </DataTableBody>
              </DataTable>
            </PanelBody>
          </Panel>
        </div>
      </div>
    </main>
  ),
};
