import type { Meta, StoryObj } from '@storybook/react';
import React from 'react';
import {
  BarChart2,
  Bell,
  Briefcase,
  Download,
  FileText,
  Globe,
  LayoutDashboard,
  Lock,
  MoreHorizontal,
  Package,
  Plus,
  RefreshCw,
  Share2,
  Shield,
  Sparkles,
  Users,
  Zap,
} from 'lucide-react';
import { Button } from '../../ui/button';
import { ChartCard, ChartConfig, DashboardBarChart, DashboardLineChart } from '../../ui/chart';
import { ActivityCard } from './ActivityCard';
import { ActivityCardSkeleton } from './ActivityCardSkeleton';
import { FeatureCard } from './FeatureCard';
import { FeatureCardSkeleton } from './FeatureCardSkeleton';
import { NotificationCard } from './NotificationCard';
import { NotificationCardSkeleton } from './NotificationCardSkeleton';
import { ProfileCard } from './ProfileCard';
import { ProfileCardSkeleton } from './ProfileCardSkeleton';
import { ProjectCard } from './ProjectCard';
import { ProjectCardSkeleton } from './ProjectCardSkeleton';
import { QuickActionCard } from './QuickActionCard';
import { QuickActionCardSkeleton } from './QuickActionCardSkeleton';

const meta: Meta = {
  title: 'Blocks/Card Patterns',
  decorators: [
    Story => (
      <div className="bg-muted rounded-xl p-8 w-full flex items-start justify-center">
        <Story />
      </div>
    ),
  ],
};
export default meta;

// ─── ActivityCard ─────────────────────────────────────────────────────────────

const ACTIVITY_ITEMS = [
  {
    id: '1',
    user: { name: 'Ana Souza', initials: 'AS' },
    action: 'criou o projeto',
    target: 'Xertica Dashboard',
    time: 'há 2 min',
    type: 'create' as const,
  },
  {
    id: '2',
    user: { name: 'Bruno Lima', initials: 'BL' },
    action: 'atualizou',
    target: 'componente Button',
    time: 'há 8 min',
    type: 'update' as const,
  },
  {
    id: '3',
    user: { name: 'Carla Rocha', initials: 'CR' },
    action: 'comentou em',
    target: 'PR #42',
    time: 'há 15 min',
    type: 'comment' as const,
  },
  {
    id: '4',
    user: { name: 'Diego Ferraz', initials: 'DF' },
    action: 'fez deploy de',
    target: 'v2.1.0',
    time: 'há 1h',
    type: 'deploy' as const,
  },
  {
    id: '5',
    user: { name: 'Elena Moura', initials: 'EM' },
    action: 'removeu',
    target: 'badge legado',
    time: 'há 2h',
    type: 'delete' as const,
  },
];

export const Activity: StoryObj = {
  render: () => (
    <ActivityCard
      items={ACTIVITY_ITEMS}
      action={
        <Button variant="ghost" size="sm">
          <MoreHorizontal className="size-4" />
        </Button>
      }
      className="max-w-md"
    />
  ),
};

// ─── ProfileCard ──────────────────────────────────────────────────────────────

export const Profile: StoryObj = {
  render: () => (
    <ProfileCard
      name="Ana Souza"
      role="Senior Frontend Engineer"
      department="Design System"
      initials="AS"
      status="online"
      stats={[
        { label: 'Projetos', value: 12 },
        { label: 'Commits', value: 348 },
        { label: 'Reviews', value: 57 },
      ]}
      primaryAction={{ label: 'Ver Perfil' }}
      secondaryAction={{ label: 'Mensagem' }}
      className="w-64"
    />
  ),
};

// ─── ProjectCard ──────────────────────────────────────────────────────────────

const MEMBERS = [
  { name: 'Ana', initials: 'AS' },
  { name: 'Bruno', initials: 'BL' },
  { name: 'Carla', initials: 'CR' },
  { name: 'Diego', initials: 'DF' },
  { name: 'Elena', initials: 'EM' },
];

export const Project: StoryObj = {
  render: () => (
    <div className="grid gap-4 md:grid-cols-2 w-full max-w-2xl">
      <ProjectCard
        title="Xertica Dashboard v3"
        description="Redesign completo do painel com novos componentes."
        status="active"
        progress={68}
        dueDate="Vence em 12 dias"
        members={MEMBERS}
      />
      <ProjectCard
        title="Design System Tokens"
        description="Migração dos tokens de design para CSS variables."
        status="review"
        progress={91}
        dueDate="Vence amanhã"
        members={MEMBERS.slice(0, 2)}
      />
      <ProjectCard
        title="App Mobile"
        description="Versão móvel do Xertica com React Native."
        status="at-risk"
        progress={34}
        dueDate="Atrasado 3 dias"
        members={MEMBERS.slice(0, 3)}
      />
      <ProjectCard
        title="Onboarding Flow"
        description="Fluxo de cadastro e primeiros passos."
        status="done"
        progress={100}
        dueDate="Entregue"
        members={MEMBERS.slice(0, 4)}
      />
    </div>
  ),
};

// ─── QuickActionCard ──────────────────────────────────────────────────────────

export const QuickActions: StoryObj = {
  render: () => (
    <div className="grid gap-4 grid-cols-2 md:grid-cols-3 max-w-2xl w-full">
      <QuickActionCard
        title="Novo Relatório"
        description="Gere relatórios personalizados de métricas."
        icon={<FileText className="size-5" />}
        actionLabel="Criar Relatório"
      />
      <QuickActionCard
        title="Convidar Membro"
        description="Adicione novos colaboradores ao workspace."
        icon={<Users className="size-5" />}
        actionLabel="Convidar"
        actionVariant="outline"
        badge="Novo"
        badgeVariant="success"
      />
      <QuickActionCard
        title="Exportar Dados"
        description="Exporte suas métricas em CSV ou JSON."
        icon={<Download className="size-5" />}
        actionLabel="Exportar"
        actionVariant="secondary"
      />
      <QuickActionCard
        title="Automação"
        description="Configure gatilhos e ações automáticas."
        icon={<Zap className="size-5" />}
        actionLabel="Configurar"
        badge="Pro"
        badgeVariant="warning"
      />
      <QuickActionCard
        title="Compartilhar"
        description="Compartilhe o dashboard com sua equipe."
        icon={<Share2 className="size-5" />}
        actionLabel="Compartilhar"
        actionVariant="outline"
      />
      <QuickActionCard
        title="Novo Projeto"
        description="Inicie um projeto a partir de um template."
        icon={<Plus className="size-5" />}
        actionLabel="Criar Projeto"
        badge="Beta"
        badgeVariant="info"
      />
    </div>
  ),
};

// ─── NotificationCard ─────────────────────────────────────────────────────────

const NOTIFICATIONS = [
  {
    id: '1',
    title: 'Deploy concluído',
    message: 'v2.1.0 foi publicado com sucesso em produção.',
    time: 'há 2 min',
    read: false,
    type: 'success' as const,
  },
  {
    id: '2',
    title: 'Revisão solicitada',
    message: 'Ana pediu revisão no PR #42: Novos tokens de cor.',
    time: 'há 10 min',
    read: false,
    type: 'info' as const,
  },
  {
    id: '3',
    title: 'Erro em produção',
    message: 'Serviço de auth com falha intermitente — 503.',
    time: 'há 1h',
    read: false,
    type: 'error' as const,
  },
  {
    id: '4',
    title: 'Licença expirando',
    message: 'Sua licença Pro expira em 7 dias. Renove para continuar.',
    time: 'há 3h',
    read: true,
    type: 'warning' as const,
  },
];

export const Notifications: StoryObj = {
  render: () => (
    <NotificationCard
      items={NOTIFICATIONS}
      onMarkAllRead={() => {}}
      onViewAll={() => {}}
      className="max-w-sm"
    />
  ),
};

// ─── ChartCard ────────────────────────────────────────────────────────────────

const REVENUE_DATA = [
  { month: 'Jan', receita: 18000, despesa: 12000 },
  { month: 'Fev', receita: 22000, despesa: 14000 },
  { month: 'Mar', receita: 19500, despesa: 13500 },
  { month: 'Abr', receita: 27000, despesa: 15000 },
  { month: 'Mai', receita: 31000, despesa: 17500 },
  { month: 'Jun', receita: 28500, despesa: 16000 },
];

const REVENUE_CONFIG: ChartConfig = {
  receita: { label: 'Receita', color: 'var(--chart-1)' },
  despesa: { label: 'Despesa', color: 'var(--chart-5)' },
};

const CHART_SERIES = [
  { key: 'receita', label: 'Receita' },
  { key: 'despesa', label: 'Despesa' },
];

export const Chart: StoryObj = {
  render: () => (
    <ChartCard
      title="Receita vs Despesa"
      description="Últimos 6 meses"
      action={
        <Button variant="ghost" size="sm">
          <RefreshCw className="size-4" />
        </Button>
      }
      footer="Dados atualizados em tempo real via API financeira."
      className="max-w-xl w-full"
      contentClassName="h-[260px]"
    >
      <DashboardBarChart
        data={REVENUE_DATA}
        config={REVENUE_CONFIG}
        series={CHART_SERIES}
        indexKey="month"
        barSize="md"
        className="h-full w-full"
      />
    </ChartCard>
  ),
};

// ─── Dashboard completo ───────────────────────────────────────────────────────

const LINE_DATA = [
  { dia: 'Seg', usuarios: 240 },
  { dia: 'Ter', usuarios: 380 },
  { dia: 'Qua', usuarios: 310 },
  { dia: 'Qui', usuarios: 470 },
  { dia: 'Sex', usuarios: 520 },
  { dia: 'Sáb', usuarios: 290 },
  { dia: 'Dom', usuarios: 180 },
];

const LINE_CONFIG: ChartConfig = {
  usuarios: { label: 'Usuários', color: 'var(--chart-1)' },
};

export const DashboardLayout: StoryObj = {
  render: () => (
    <div className="grid gap-4 w-full max-w-5xl">
      <div className="grid gap-4 md:grid-cols-3">
        <QuickActionCard
          title="Novo Projeto"
          description="Inicie a partir de um template."
          icon={<Briefcase className="size-5" />}
          actionLabel="Criar"
        />
        <QuickActionCard
          title="Convidar Equipe"
          description="Adicione membros ao workspace."
          icon={<Users className="size-5" />}
          actionLabel="Convidar"
          actionVariant="outline"
        />
        <QuickActionCard
          title="Ver Relatórios"
          description="Métricas e KPIs do período."
          icon={<BarChart2 className="size-5" />}
          actionLabel="Abrir"
          actionVariant="secondary"
          badge="Novo"
          badgeVariant="success"
        />
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <div className="md:col-span-2">
          <ChartCard title="Usuários Ativos" description="Esta semana" contentClassName="h-[220px]">
            <DashboardLineChart
              data={LINE_DATA}
              config={LINE_CONFIG}
              series={[{ key: 'usuarios', label: 'Usuários' }]}
              indexKey="dia"
              className="h-full w-full"
            />
          </ChartCard>
        </div>
        <NotificationCard title="Alertas" items={NOTIFICATIONS.slice(0, 3)} onViewAll={() => {}} />
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <ActivityCard items={ACTIVITY_ITEMS} className="h-full" />
        <div className="grid gap-4">
          <ProfileCard
            name="Ana Souza"
            role="Product Designer"
            initials="AS"
            status="online"
            stats={[
              { label: 'Projetos', value: 12 },
              { label: 'Tarefas', value: 34 },
              { label: 'Reviews', value: 8 },
            ]}
          />
          <ProjectCard
            title="Xertica Dashboard v3"
            status="active"
            progress={68}
            dueDate="12 dias restantes"
            members={MEMBERS.slice(0, 3)}
          />
        </div>
      </div>
    </div>
  ),
};

// ─── FeatureCard ──────────────────────────────────────────────────────────────

export const Feature: StoryObj = {
  render: () => (
    <FeatureCard
      title="Template CLI"
      description="Página de template pronta para uso CLI com todos os componentes configurados."
      icon={<FileText />}
      color="chart-2"
      badge="Novo"
      actionLabel="Visualizar"
    />
  ),
};

export const FeatureColors: StoryObj = {
  render: () => (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 w-full max-w-4xl">
      <FeatureCard
        title="Dashboard"
        description="Visualize métricas e KPIs em tempo real com gráficos interativos."
        icon={<LayoutDashboard />}
        color="primary"
        badge="Popular"
        badgeVariant="default"
        actionLabel="Abrir"
      />
      <FeatureCard
        title="Integrações"
        description="Conecte APIs externas e serviços de terceiros com um clique."
        icon={<Globe />}
        color="chart-1"
        actionLabel="Explorar"
      />
      <FeatureCard
        title="Automação"
        description="Crie fluxos automáticos com gatilhos e ações personalizadas."
        icon={<Zap />}
        color="chart-2"
        badge="Beta"
        badgeVariant="warning"
        actionLabel="Configurar"
      />
      <FeatureCard
        title="IA Generativa"
        description="Potencialize sua equipe com assistentes inteligentes e geração de conteúdo."
        icon={<Sparkles />}
        color="chart-3"
        badge="Pro"
        badgeVariant="info"
        actionLabel="Ativar"
      />
      <FeatureCard
        title="Equipes"
        description="Gerencie membros, permissões e workspaces de forma centralizada."
        icon={<Users />}
        color="chart-4"
        actionLabel="Gerenciar"
      />
      <FeatureCard
        title="Pacotes"
        description="Publique e distribua seus componentes como biblioteca reutilizável."
        icon={<Package />}
        color="chart-5"
        actionLabel="Publicar"
      />
    </div>
  ),
};

export const FeatureSemanticColors: StoryObj = {
  render: () => (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 w-full max-w-4xl">
      <FeatureCard
        title="Segurança"
        description="Proteção avançada com autenticação multifator e logs de auditoria."
        icon={<Shield />}
        color="success"
        actionLabel="Configurar"
      />
      <FeatureCard
        title="Insights"
        description="Análises aprofundadas com relatórios automáticos e alertas inteligentes."
        icon={<BarChart2 />}
        color="info"
        actionLabel="Ver Dados"
      />
      <FeatureCard
        title="Permissões"
        description="Controle granular de acessos por função, projeto e recurso."
        icon={<Lock />}
        color="warning"
        badge="Atenção"
        badgeVariant="warning"
        actionLabel="Revisar"
      />
      <FeatureCard
        title="Compartilhar"
        description="Distribua relatórios e dashboards com stakeholders externos."
        icon={<Share2 />}
        color="destructive"
        badge="Restrito"
        badgeVariant="destructive"
        actionLabel="Solicitar"
      />
    </div>
  ),
};

// ─── Skeletons ────────────────────────────────────────────────────────────────

type SkeletonStory = StoryObj;

/** All card-pattern skeletons side by side to compare proportions with their data counterparts. */
export const SkeletonShowcase: SkeletonStory = {
  name: 'Skeletons / All Card Patterns',
  render: () => (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 w-full max-w-5xl">
      <ActivityCardSkeleton rows={4} />
      <ProfileCardSkeleton showStats showActions />
      <ProjectCardSkeleton memberCount={3} />
      <NotificationCardSkeleton rows={3} showViewAll />
      <QuickActionCardSkeleton />
      <FeatureCardSkeleton showAction />
    </div>
  ),
};

export const ActivitySkeleton: SkeletonStory = {
  name: 'Skeletons / ActivityCard',
  render: () => (
    <div className="w-[380px]">
      <ActivityCardSkeleton rows={5} />
    </div>
  ),
};

export const ProfileSkeleton: SkeletonStory = {
  name: 'Skeletons / ProfileCard',
  render: () => (
    <div className="w-[280px]">
      <ProfileCardSkeleton showStats showActions />
    </div>
  ),
};

export const ProjectSkeleton: SkeletonStory = {
  name: 'Skeletons / ProjectCard',
  render: () => (
    <div className="w-[320px]">
      <ProjectCardSkeleton memberCount={4} />
    </div>
  ),
};

export const NotificationSkeleton: SkeletonStory = {
  name: 'Skeletons / NotificationCard',
  render: () => (
    <div className="w-[400px]">
      <NotificationCardSkeleton rows={4} showViewAll />
    </div>
  ),
};

export const QuickActionSkeleton: SkeletonStory = {
  name: 'Skeletons / QuickActionCard',
  render: () => (
    <div className="w-[260px]">
      <QuickActionCardSkeleton />
    </div>
  ),
};

export const FeatureSkeleton: SkeletonStory = {
  name: 'Skeletons / FeatureCard',
  render: () => (
    <div className="w-[300px]">
      <FeatureCardSkeleton showAction />
    </div>
  ),
};
