import {
  Activity,
  AlertTriangle,
  CheckCircle,
  CreditCard,
  Crown,
  Gift,
  Percent,
  Shield,
  TrendingUp,
  UserCircle,
  Users,
  XCircle,
} from 'lucide-react';

import { Suspense, lazy } from 'react';

import { Head, Link } from '@inertiajs/react';

import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbList,
  BreadcrumbPage,
} from '@/Components/ui/breadcrumb';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { Progress } from '@/Components/ui/progress';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime, formatNumber } from '@/lib/format';
import type { AdminDashboardProps } from '@/types/admin';

// Lazy load chart components
const LazyAdminAreaChart = lazy(async () => {
  const module = await import('@/Components/admin/AdminCharts');
  return { default: module.AdminAreaChart };
});

// Area chart skeleton: mimics an area chart with axes + wave shape
const AreaChartSkeleton = () => (
  <div className="h-[250px] w-full space-y-3 p-2">
    <div className="flex h-full gap-2">
      <div className="flex flex-col justify-between py-2">
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} className="h-3 w-6" />
        ))}
      </div>
      <div className="flex-1 flex flex-col justify-end gap-0.5">
        <Skeleton className="w-full rounded-t-lg" style={{ height: '40%' }} />
      </div>
    </div>
    <div className="flex justify-between px-8">
      {Array.from({ length: 6 }).map((_, i) => (
        <Skeleton key={i} className="h-3 w-10" />
      ))}
    </div>
  </div>
);


const REASON_LABELS: Record<string, string> = {
  too_expensive: 'Too Expensive',
  missing_features: 'Missing Features',
  not_using_it: 'Not Using It',
  switching_competitor: 'Switching to Competitor',
  technical_issues: 'Technical Issues',
  other: 'Other',
};

export default function AdminDashboard({
  stats,
  signup_chart,
  activation_funnel,
  recent_activity,
  cancellation_reasons,
  operational_health,
  last_refreshed_at,
}: AdminDashboardProps) {
  const statCards: StatCard[] = [
    {
      title: 'Total Users',
      value: stats.total_users,
      icon: Users,
      description: 'All registered users',
      href: '/admin/users',
    },
    {
      title: 'New (7d)',
      value: stats.new_users_7d,
      icon: TrendingUp,
      description: 'Signups this week',
      href: '/admin/users?sort=created_at&dir=desc',
    },
    {
      title: 'New (30d)',
      value: stats.new_users_30d,
      icon: TrendingUp,
      description: 'Signups this month',
      href: '/admin/users?sort=created_at&dir=desc',
    },
    {
      title: 'Admins',
      value: stats.admin_count,
      icon: Shield,
      description: 'Admin accounts',
      href: '/admin/users?admin=1',
    },
  ];

  // Plan tier breakdown (when billing is enabled)
  const planTierCards: StatCard[] = [];
  if (stats.free_users !== undefined) {
    planTierCards.push({
      title: 'Free Users',
      value: stats.free_users,
      icon: UserCircle,
      description: 'Users on free tier',
      href: '/admin/users?tier=free',
    });
  }
  if (stats.trial_users !== undefined) {
    planTierCards.push({
      title: 'Trial Users',
      value: stats.trial_users,
      icon: Gift,
      description: 'Active trial period',
      href: '/admin/users?tier=trial',
    });
  }
  if (stats.paid_users !== undefined) {
    planTierCards.push({
      title: 'Paid Users',
      value: stats.paid_users,
      icon: Crown,
      description: 'Active subscribers',
      href: '/admin/billing/subscriptions?status=active',
    });
  }

  if (stats.active_subscriptions !== undefined) {
    statCards.push({
      title: 'Active Subscriptions',
      value: stats.active_subscriptions,
      icon: CreditCard,
      description: 'Paying customers',
      href: '/admin/billing/subscriptions?status=active',
    });
  }

  // Trial conversion metric (billing feature)
  if (stats.trial_conversion_rate !== undefined) {
    statCards.push({
      title: 'Trial Conversion',
      value: stats.trial_conversion_rate,
      icon: Percent,
      format: (n: number) => `${n}%`,
      description: 'Trial to paid conversion',
      href: '/admin/users?tier=trial',
    });
  }

  return (
    <AdminLayout>
      <Head title="Admin Dashboard" />
      <div className="container pt-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbPage>Admin Dashboard</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
      </div>
      <div className="flex items-start justify-between gap-4">
        <PageHeader title="Admin Dashboard" subtitle="System overview and metrics" />
        <span className="shrink-0 text-xs text-muted-foreground">
          Updated {formatRelativeTime(last_refreshed_at)}
        </span>
      </div>

      <div className="container py-6 space-y-6">
        <AdminStatsGrid stats={statCards} />

        {/* Plan Tier Breakdown */}
        {planTierCards.length > 0 && (
          <AdminStatsGrid stats={planTierCards} columns="grid-cols-1 md:grid-cols-3" />
        )}

        {/* Operational Health */}
        {operational_health && (
          <Card>
            <CardHeader>
              <CardTitle>Operational Health</CardTitle>
              <CardDescription>System health metrics and circuit breaker status</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <div className="flex items-center gap-3 rounded-lg border p-3">
                  <Activity className="h-5 w-5 text-muted-foreground" />
                  <div>
                    <p className="text-sm font-medium">Queue Size</p>
                    <p className="text-2xl font-bold">{operational_health.queue_size}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3 rounded-lg border p-3">
                  {operational_health.failed_jobs_1h > 0 ? (
                    <AlertTriangle className="h-5 w-5 text-destructive" />
                  ) : (
                    <CheckCircle className="h-5 w-5 text-success" />
                  )}
                  <div>
                    <p className="text-sm font-medium">Failed Jobs (1h)</p>
                    <p className="text-2xl font-bold">{operational_health.failed_jobs_1h}</p>
                  </div>
                </div>
                <Link
                  href="/admin/circuit-breaker"
                  className="flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50"
                >
                  <Shield className="h-5 w-5 text-muted-foreground" />
                  <div>
                    <p className="text-sm font-medium">Circuit Breakers</p>
                    <div className="mt-1 flex flex-wrap gap-1">
                      {Object.entries(operational_health.circuit_breakers).map(
                        ([service, state]) => (
                          <Badge
                            key={service}
                            variant={state === 'closed' ? 'secondary' : 'destructive'}
                          >
                            {service}: {state}
                          </Badge>
                        ),
                      )}
                    </div>
                  </div>
                </Link>
                <div className="flex items-center gap-3 rounded-lg border p-3">
                  <TrendingUp className="h-5 w-5 text-muted-foreground" />
                  <div>
                    <p className="text-sm font-medium">Last GSC Sync</p>
                    <p className="text-sm text-muted-foreground">
                      {operational_health.last_gsc_sync
                        ? formatRelativeTime(operational_health.last_gsc_sync)
                        : 'Never'}
                    </p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Signup Chart */}
        <Card>
          <CardHeader>
            <CardTitle>User Signups</CardTitle>
            <CardDescription>New user registrations over the last 30 days</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartErrorBoundary>
              <Suspense fallback={<AreaChartSkeleton />}>
                <LazyAdminAreaChart
                  data={signup_chart}
                  dataKey="count"
                  name="Signups"
                  gradientId="signupGradient"
                  emptyIcon={TrendingUp}
                  emptyTitle="No signups yet"
                  emptyDescription="User signup data will appear here."
                />
              </Suspense>
            </ChartErrorBoundary>
          </CardContent>
        </Card>

        {/* Activation Funnel */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              Activation Funnel
              {activation_funnel.activation_rate > 0 && (
                <span className="text-sm font-normal text-muted-foreground">
                  {activation_funnel.activation_rate}% activation rate
                </span>
              )}
            </CardTitle>
            <CardDescription>
              User progression through key milestones (last 30 days)
            </CardDescription>
          </CardHeader>
          <CardContent>
            {activation_funnel.stages.length === 0 ? (
              <EmptyState
                icon={TrendingUp}
                title="No funnel data yet"
                description="Funnel metrics appear once users start signing up."
                size="sm"
              />
            ) : (
              <div className="space-y-3">
                {activation_funnel.stages.map((stage) => (
                  <div key={stage.name} className="space-y-1">
                    <div className="flex items-center justify-between text-sm">
                      <span className="font-medium">{stage.name}</span>
                      <span className="text-muted-foreground">
                        {formatNumber(stage.users)} ({stage.rate}%)
                      </span>
                    </div>
                    <Progress value={stage.rate} className="h-2" />
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card>
          <CardHeader>
            <CardTitle>Recent Activity</CardTitle>
            <CardDescription>Latest audit log entries</CardDescription>
          </CardHeader>
          <CardContent className="p-0">
            {recent_activity.length === 0 ? (
              <EmptyState
                icon={Activity}
                title="No activity recorded yet"
                description="Audit log entries will appear here as users interact with the app."
                size="sm"
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Event</TableHead>
                      <TableHead>User</TableHead>
                      <TableHead>IP</TableHead>
                      <TableHead>Time</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {recent_activity.map((log) => (
                      <TableRow key={log.id} className="hover:bg-muted/50">
                        <TableCell>
                          <Link
                            href={`/admin/audit-logs/${log.id}`}
                            className="hover:opacity-80 transition-opacity"
                          >
                            <Badge variant="secondary">{log.event}</Badge>
                          </Link>
                        </TableCell>
                        <TableCell className="text-sm">
                          {log.user_id ? (
                            <Link
                              href={`/admin/users/${log.user_id}`}
                              className="hover:underline"
                              aria-label={`View user: ${log.user_name ?? `User #${log.user_id}`}`}
                            >
                              {log.user_name ?? `User #${log.user_id}`}
                            </Link>
                          ) : (
                            <span className="text-muted-foreground">System</span>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground font-mono">
                          {log.ip}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatRelativeTime(log.created_at)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
          <CardFooter className="border-t pt-3 pb-3">
            <Link
              href="/admin/audit-logs?admin_actions_only=1"
              className="text-xs text-muted-foreground hover:text-foreground transition-colors"
            >
              View admin actions only →
            </Link>
          </CardFooter>
        </Card>
        {/* Cancellation Reasons */}
        {cancellation_reasons && cancellation_reasons.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <XCircle className="h-5 w-5 text-muted-foreground" />
                Cancellation Reasons
              </CardTitle>
              <CardDescription>Why users cancelled — all time</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Reason</TableHead>
                    <TableHead className="text-right">Count</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {cancellation_reasons.map((row) => (
                    <TableRow key={row.reason ?? 'unknown'}>
                      <TableCell>
                        {REASON_LABELS[row.reason ?? ''] ?? row.reason ?? 'Not specified'}
                      </TableCell>
                      <TableCell className="text-right font-mono text-sm">
                        {row.count}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )}
      </div>
    </AdminLayout>
  );
}
