'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { useAnalytics, TimeRange } from '@/hooks/use-analytics'
import { StatCard } from '@/components/analytics/stat-card'
import { LineChart } from '@/components/analytics/line-chart'
import { BarChart } from '@/components/analytics/bar-chart'
import { DonutChart } from '@/components/analytics/donut-chart'
import { AnalyticsSection } from '@/components/analytics/analytics-section'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  ShoppingCart,
  Users,
  CreditCard,
  CheckCircle,
  RefreshCw,
  AlertCircle,
  TrendingUp,
} from 'lucide-react'
import { cn } from '@/lib/utils'

const TIME_RANGES: { value: TimeRange; label: string }[] = [
  { value: '7d', label: '7 Days' },
  { value: '30d', label: '30 Days' },
  { value: '90d', label: '90 Days' },
]

// Status colors
const STATUS_COLORS: Record<string, string> = {
  PENDING_PAYMENT: 'hsl(45, 90%, 50%)',
  AWAITING_DNS: 'hsl(30, 80%, 55%)',
  DNS_VERIFIED: 'hsl(190, 70%, 45%)',
  PROVISIONING: 'hsl(220, 70%, 50%)',
  FULFILLED: 'hsl(160, 60%, 45%)',
  EMAIL_CONFIGURED: 'hsl(140, 70%, 40%)',
  FAILED: 'hsl(350, 70%, 50%)',
  CANCELLED: 'hsl(0, 0%, 50%)',
}

// Plan colors
const PLAN_COLORS: Record<string, string> = {
  TRIAL: 'hsl(45, 90%, 50%)',
  STARTER: 'hsl(220, 70%, 50%)',
  PRO: 'hsl(160, 60%, 45%)',
  ENTERPRISE: 'hsl(280, 60%, 50%)',
}

export default function AnalyticsPage() {
  const [timeRange, setTimeRange] = useState<TimeRange>('30d')
  const { data, isLoading, error, refetch, isFetching } = useAnalytics(timeRange)

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
        <AlertCircle className="h-12 w-12 text-destructive" />
        <p className="text-lg text-muted-foreground">Failed to load analytics</p>
        <Button onClick={() => refetch()} variant="outline">
          Try Again
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Analytics</h1>
          <p className="text-muted-foreground">
            Platform performance and insights
          </p>
        </div>
        <div className="flex items-center gap-2">
          <div className="flex rounded-lg border p-1">
            {TIME_RANGES.map((range) => (
              <Button
                key={range.value}
                variant={timeRange === range.value ? 'secondary' : 'ghost'}
                size="sm"
                onClick={() => setTimeRange(range.value)}
                className="px-3"
              >
                {range.label}
              </Button>
            ))}
          </div>
          <Button
            variant="outline"
            size="icon"
            onClick={() => refetch()}
            disabled={isFetching}
          >
            <RefreshCw className={cn('h-4 w-4', isFetching && 'animate-spin')} />
          </Button>
        </div>
      </div>

      {/* Overview Stats */}
      {isLoading ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} className="h-[120px]" />
          ))}
        </div>
      ) : data ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <StatCard
            title="Total Orders"
            value={data.overview.totalOrders.toLocaleString()}
            trend={data.overview.ordersTrend}
            icon={<ShoppingCart className="h-5 w-5" />}
          />
          <StatCard
            title="Active Customers"
            value={data.overview.activeCustomers.toLocaleString()}
            trend={data.overview.customersTrend}
            icon={<Users className="h-5 w-5" />}
          />
          <StatCard
            title="Active Subscriptions"
            value={data.overview.activeSubscriptions.toLocaleString()}
            icon={<CreditCard className="h-5 w-5" />}
          />
          <StatCard
            title="Success Rate"
            value={`${data.overview.successRate}%`}
            icon={<CheckCircle className="h-5 w-5" />}
          />
        </div>
      ) : null}

      {/* Order Analytics */}
      <AnalyticsSection
        title="Order Analytics"
        description="Order volume and status distribution"
      >
        {isLoading ? (
          <>
            <Skeleton className="h-[350px]" />
            <Skeleton className="h-[350px]" />
          </>
        ) : data ? (
          <>
            <LineChart
              title="Orders Over Time"
              data={data.orders.byDay.map((d) => ({
                date: d.date,
                orders: d.count,
              }))}
              lines={[{ dataKey: 'orders', color: 'hsl(var(--primary))' }]}
            />
            <DonutChart
              title="Orders by Status"
              data={Object.entries(data.orders.byStatus)
                .filter(([, count]) => count > 0)
                .map(([status, count]) => ({
                  name: formatStatus(status),
                  value: count,
                  color: STATUS_COLORS[status],
                }))}
              centerValue={data.overview.totalOrders}
              centerLabel="Total"
            />
          </>
        ) : null}
      </AnalyticsSection>

      {/* Customer Insights */}
      <AnalyticsSection
        title="Customer Insights"
        description="Customer growth and subscription distribution"
      >
        {isLoading ? (
          <>
            <Skeleton className="h-[350px]" />
            <Skeleton className="h-[350px]" />
          </>
        ) : data ? (
          <>
            <LineChart
              title="Customer Growth"
              data={data.customers.growthByDay.map((d) => ({
                date: d.date,
                customers: d.count,
              }))}
              lines={[{ dataKey: 'customers', color: 'hsl(160, 60%, 45%)' }]}
            />
            <BarChart
              title="Subscriptions by Plan"
              data={Object.entries(data.customers.byPlan)
                .filter(([, count]) => count > 0)
                .map(([plan, count]) => ({
                  name: formatPlan(plan),
                  value: count,
                  color: PLAN_COLORS[plan],
                }))}
            />
          </>
        ) : null}
      </AnalyticsSection>

      {/* Token Usage */}
      <AnalyticsSection
        title="Token Usage"
        description="AI token consumption and top consumers"
      >
        {isLoading ? (
          <>
            <Skeleton className="h-[350px]" />
            <Skeleton className="h-[350px]" />
          </>
        ) : data ? (
          <>
            <LineChart
              title="Token Usage Over Time"
              data={data.tokens.usageByDay.map((d) => ({
                date: d.date,
                tokens: d.tokens,
              }))}
              lines={[{ dataKey: 'tokens', color: 'hsl(280, 60%, 50%)' }]}
            />
            <BarChart
              title="Top Token Consumers"
              data={data.tokens.topConsumers.slice(0, 5).map((c) => ({
                name: c.name.length > 15 ? c.name.substring(0, 15) + '...' : c.name,
                value: c.tokens,
              }))}
              horizontal
            />
          </>
        ) : null}
      </AnalyticsSection>

      {/* Provisioning Performance */}
      <AnalyticsSection
        title="Provisioning Performance"
        description="Automation mode and recent failures"
      >
        {isLoading ? (
          <>
            <Skeleton className="h-[350px]" />
            <Skeleton className="h-[350px]" />
          </>
        ) : data ? (
          <>
            <DonutChart
              title="Orders by Automation Mode"
              data={Object.entries(data.provisioning.byAutomation)
                .filter(([, count]) => count > 0)
                .map(([mode, count]) => ({
                  name: formatMode(mode),
                  value: count,
                }))}
              centerValue={`${data.provisioning.successRate}%`}
              centerLabel="Success Rate"
            />
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-base font-medium flex items-center gap-2">
                  <AlertCircle className="h-4 w-4 text-destructive" />
                  Recent Failures
                </CardTitle>
              </CardHeader>
              <CardContent>
                {data.provisioning.recentFailures.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                    <CheckCircle className="h-8 w-8 mb-2 text-green-500" />
                    <p>No recent failures</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {data.provisioning.recentFailures.slice(0, 5).map((failure) => (
                      <div
                        key={failure.orderId}
                        className="flex items-start justify-between p-3 rounded-lg bg-muted/50"
                      >
                        <div className="space-y-1">
                          <p className="font-medium text-sm">{failure.domain}</p>
                          <p className="text-xs text-muted-foreground line-clamp-2">
                            {failure.reason}
                          </p>
                        </div>
                        <p className="text-xs text-muted-foreground whitespace-nowrap ml-4">
                          {formatDate(failure.date)}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </>
        ) : null}
      </AnalyticsSection>
    </div>
  )
}

function formatStatus(status: string): string {
  return status
    .replace(/_/g, ' ')
    .toLowerCase()
    .replace(/\b\w/g, (l) => l.toUpperCase())
}

function formatPlan(plan: string): string {
  return plan.charAt(0) + plan.slice(1).toLowerCase()
}

function formatMode(mode: string): string {
  return mode.charAt(0) + mode.slice(1).toLowerCase()
}

function formatDate(dateStr: string): string {
  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (diffHours < 1) return 'Just now'
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 7) return `${diffDays}d ago`
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}
