'use client';

import { useState, useEffect } from 'react';
import { Zap, BarChart3, DollarSign, Cpu, X, User as UserIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  mockDailyMetrics,
  mockUsers,
  formatNumber,
  formatCurrency,
  type DailyMetric,
  type User,
} from '@/lib/mock-data';
import {
  apiGetUsage,
  apiGetUsageSummary,
  apiListUsers,
  apiGetRetention,
  type ApiUsageRecord,
  type ApiModelBreakdown,
  type ApiSourceBreakdown,
  type ApiProductBreakdown,
  type RetentionCohort,
} from '@/lib/api';
import { Separator } from '@/components/ui/separator';
import { AreaChart, BarChart, Donut } from '@/components/charts';
import { seriesValues, dateBars, donutSlices } from '@/lib/chart-data';

// Categorical palette drawn from admin's shadcn chart tokens (no literals).
const COLORS = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-4)', 'var(--chart-5)'];

function usageRecordsToDailyMetrics(records: ApiUsageRecord[]): DailyMetric[] {
  const byDate = new Map<string, DailyMetric>();
  for (const r of records) {
    const existing = byDate.get(r.date);
    if (existing) {
      existing.totalTokens += r.tokensUsed;
      existing.totalRequests += r.dictations;
      existing.revenue += r.costUsd;
      existing.activeUsers += 1;
    } else {
      byDate.set(r.date, {
        date: r.date,
        activeUsers: 1,
        totalRequests: r.dictations,
        totalTokens: r.tokensUsed,
        revenue: r.costUsd,
      });
    }
  }
  return Array.from(byDate.values()).sort((a, b) => a.date.localeCompare(b.date));
}

export default function UsagePage() {
  const [timeRange, setTimeRange] = useState('30d');
  const [dailyMetrics, setDailyMetrics] = useState<DailyMetric[]>(mockDailyMetrics);
  const [modelUsage, setModelUsage] = useState<(ApiModelBreakdown & { percentage: number })[]>([]);
  const [sourceUsage, setSourceUsage] = useState<(ApiSourceBreakdown & { percentage: number })[]>(
    []
  );
  const [productUsage, setProductUsage] = useState<
    (ApiProductBreakdown & { percentage: number })[]
  >([]);
  const [users, setUsers] = useState<User[]>(mockUsers);
  const [cohorts, setCohorts] = useState<RetentionCohort[]>([]);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [productFilter, setProductFilter] = useState<string>('current');

  useEffect(() => {
    const days = timeRange === '7d' ? 7 : timeRange === '90d' ? 90 : 30;
    const uid = selectedUserId || undefined;
    const pid = productFilter === 'current' ? undefined : productFilter;
    apiGetUsage(days, uid, pid).then(({ data }) => {
      if (data?.records?.length) {
        setDailyMetrics(usageRecordsToDailyMetrics(data.records));
      } else {
        setDailyMetrics([]);
      }
    });
    apiGetUsageSummary(days, uid, pid).then(({ data }) => {
      if (data?.modelBreakdown?.length) {
        const totalCost = data.modelBreakdown.reduce((s, m) => s + m.cost, 0);
        setModelUsage(
          data.modelBreakdown.map(m => ({
            ...m,
            percentage: totalCost > 0 ? Math.round((m.cost / totalCost) * 100) : 0,
          }))
        );
      } else {
        setModelUsage([]);
      }
      if (data?.sourceBreakdown?.length) {
        const totalTokens = data.sourceBreakdown.reduce((s, m) => s + m.tokens, 0);
        setSourceUsage(
          data.sourceBreakdown.map(m => ({
            ...m,
            percentage: totalTokens > 0 ? Math.round((m.tokens / totalTokens) * 100) : 0,
          }))
        );
      } else {
        setSourceUsage([]);
      }
      if (data?.productBreakdown?.length) {
        const totalTokens = data.productBreakdown.reduce((s, m) => s + m.tokens, 0);
        setProductUsage(
          data.productBreakdown.map(m => ({
            ...m,
            percentage: totalTokens > 0 ? Math.round((m.tokens / totalTokens) * 100) : 0,
          }))
        );
      } else {
        setProductUsage([]);
      }
    });
    apiGetRetention(8).then(({ data }) => {
      if (data?.cohorts) setCohorts(data.cohorts);
    });
    apiListUsers().then(({ data }) => {
      if (data?.users?.length) {
        setUsers(
          data.users.map(u => ({
            id: u.id,
            name: u.name,
            email: u.email,
            plan: u.plan as User['plan'],
            status: u.status as User['status'],
            createdAt: u.createdAt,
            lastActive: u.lastActive,
            totalTokensUsed: u.totalTokensUsed,
            totalRequests: u.totalRequests,
            monthlySpend: u.monthlySpend,
          }))
        );
      }
    });
  }, [timeRange, selectedUserId, productFilter]);

  const totalTokens = dailyMetrics.reduce((s, d) => s + d.totalTokens, 0);
  const totalRequests = dailyMetrics.reduce((s, d) => s + d.totalRequests, 0);
  const totalRevenue = dailyMetrics.reduce((s, d) => s + d.revenue, 0);
  const totalModelCost = modelUsage.reduce((s, m) => s + m.cost, 0);

  const topUsers = [...users].sort((a, b) => b.totalTokensUsed - a.totalTokensUsed).slice(0, 5);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Usage Analytics</h1>
          <p className="text-muted-foreground">
            Monitor token consumption, API requests, and model usage
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Select value={productFilter} onValueChange={setProductFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="current">Current Product</SelectItem>
              <SelectItem value="_all">All Products</SelectItem>
            </SelectContent>
          </Select>
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-[150px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7d">Last 7 days</SelectItem>
              <SelectItem value="30d">Last 30 days</SelectItem>
              <SelectItem value="90d">Last 90 days</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* User Filter Banner */}
      {selectedUserId && (
        <Card className="border-blue-500/50 bg-blue-50 dark:bg-blue-950/30">
          <CardContent className="pt-4 pb-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <UserIcon className="h-4 w-4 text-blue-600" />
                <span className="text-sm font-medium text-blue-800 dark:text-blue-200">
                  Viewing usage for:{' '}
                  {users.find(u => u.id === selectedUserId)?.name || selectedUserId}
                </span>
                <span className="text-xs text-blue-600 dark:text-blue-400">
                  ({users.find(u => u.id === selectedUserId)?.email})
                </span>
              </div>
              <Button
                size="sm"
                variant="ghost"
                className="text-blue-700 hover:text-blue-900"
                onClick={() => setSelectedUserId(null)}
              >
                <X className="mr-1 h-3.5 w-3.5" />
                Clear Filter
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Tokens
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <Zap className="h-5 w-5 text-blue-500" />
              <span className="text-2xl font-bold">{formatNumber(totalTokens)}</span>
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {formatNumber(Math.round(totalTokens / 30))}/day avg
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Requests
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <BarChart3 className="h-5 w-5 text-emerald-500" />
              <span className="text-2xl font-bold">{formatNumber(totalRequests)}</span>
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {formatNumber(Math.round(totalRequests / 30))}/day avg
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Revenue
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <DollarSign className="h-5 w-5 text-amber-500" />
              <span className="text-2xl font-bold">{formatCurrency(totalRevenue)}</span>
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {formatCurrency(totalRevenue / 30)}/day avg
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Model Costs (Azure)
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <Cpu className="h-5 w-5 text-violet-500" />
              <span className="text-2xl font-bold">{formatCurrency(totalModelCost)}</span>
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              Margin: {formatCurrency(totalRevenue - totalModelCost)}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Charts Row 1 */}
      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Token Consumption (30 days)</CardTitle>
          </CardHeader>
          <CardContent>
            <AreaChart
              values={seriesValues(dailyMetrics, 'totalTokens')}
              width={640}
              height={300}
              className="h-auto w-full"
              ariaLabel="Token consumption over the last 30 days"
            />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">API Requests (30 days)</CardTitle>
          </CardHeader>
          <CardContent>
            <BarChart
              data={dateBars(dailyMetrics, 'totalRequests')}
              width={640}
              height={300}
              className="h-auto w-full"
              ariaLabel="API requests over the last 30 days"
            />
          </CardContent>
        </Card>
      </div>

      {/* Charts Row 2: Pie + Top Users */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Model Distribution Pie */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Model Distribution by Cost</CardTitle>
          </CardHeader>
          <CardContent className="flex justify-center">
            <Donut
              slices={donutSlices(modelUsage, 'model', 'cost').map((s, idx) => ({
                ...s,
                color: COLORS[idx % COLORS.length],
              }))}
              size={260}
              ariaLabel="Model distribution by cost"
            />
          </CardContent>
        </Card>

        {/* Top Users by Token Usage */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">
              Top Users by Token Usage
              <span className="text-xs font-normal text-muted-foreground ml-2">
                (click to drill down)
              </span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Rank</TableHead>
                  <TableHead>User</TableHead>
                  <TableHead>Plan</TableHead>
                  <TableHead className="text-right">Tokens</TableHead>
                  <TableHead className="text-right">Requests</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {topUsers.map((user, idx) => (
                  <TableRow
                    key={user.id}
                    className={`cursor-pointer hover:bg-muted/50 ${selectedUserId === user.id ? 'bg-blue-50 dark:bg-blue-950/30' : ''}`}
                    onClick={() => setSelectedUserId(selectedUserId === user.id ? null : user.id)}
                  >
                    <TableCell>
                      <Badge
                        variant="secondary"
                        className={
                          idx === 0
                            ? 'bg-amber-50 text-amber-700'
                            : idx === 1
                              ? 'bg-slate-100 text-slate-600'
                              : idx === 2
                                ? 'bg-orange-50 text-orange-700'
                                : ''
                        }
                      >
                        #{idx + 1}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p className="font-medium text-sm">{user.name}</p>
                        <p className="text-xs text-muted-foreground">{user.email}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant="secondary"
                        className={
                          user.plan === 'enterprise'
                            ? 'bg-violet-50 text-violet-700'
                            : user.plan === 'pro'
                              ? 'bg-blue-50 text-blue-700'
                              : ''
                        }
                      >
                        {user.plan}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(user.totalTokensUsed)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(user.totalRequests)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>

      {/* Detailed Model Breakdown */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Model Usage Breakdown</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Model</TableHead>
                <TableHead className="text-right">Tokens</TableHead>
                <TableHead className="text-right">Requests</TableHead>
                <TableHead className="text-right">Cost</TableHead>
                <TableHead className="text-right">% of Total</TableHead>
                <TableHead className="text-right">Cost/1K Tokens</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {modelUsage.map(model => (
                <TableRow key={model.model}>
                  <TableCell className="font-medium">{model.model}</TableCell>
                  <TableCell className="text-right font-mono">
                    {formatNumber(model.tokens)}
                  </TableCell>
                  <TableCell className="text-right font-mono">
                    {formatNumber(model.requests)}
                  </TableCell>
                  <TableCell className="text-right font-mono">
                    {formatCurrency(model.cost)}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <div className="h-2 w-16 rounded-full bg-muted overflow-hidden">
                        <div
                          className="h-full rounded-full bg-primary"
                          style={{ width: `${model.percentage}%` }}
                        />
                      </div>
                      <span className="text-sm">{model.percentage}%</span>
                    </div>
                  </TableCell>
                  <TableCell className="text-right font-mono text-sm">
                    {formatCurrency((model.cost / model.tokens) * 1000)}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
      {/* Platform / Source Breakdown */}
      {sourceUsage.length > 0 && (
        <div className="grid gap-6 lg:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Usage by Platform</CardTitle>
            </CardHeader>
            <CardContent className="flex justify-center">
              <Donut
                slices={donutSlices(sourceUsage, 'source', 'tokens').map((s, idx) => ({
                  ...s,
                  color: COLORS[idx % COLORS.length],
                }))}
                size={240}
                ariaLabel="Token usage by platform"
              />
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Platform Breakdown</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Platform</TableHead>
                    <TableHead className="text-right">Tokens</TableHead>
                    <TableHead className="text-right">Requests</TableHead>
                    <TableHead className="text-right">Cost</TableHead>
                    <TableHead className="text-right">% of Tokens</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sourceUsage.map(src => (
                    <TableRow key={src.source}>
                      <TableCell className="font-medium capitalize">{src.source}</TableCell>
                      <TableCell className="text-right font-mono">
                        {formatNumber(src.tokens)}
                      </TableCell>
                      <TableCell className="text-right font-mono">
                        {formatNumber(src.requests)}
                      </TableCell>
                      <TableCell className="text-right font-mono">
                        {formatCurrency(src.cost)}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-2">
                          <div className="h-2 w-16 rounded-full bg-muted overflow-hidden">
                            <div
                              className="h-full rounded-full bg-primary"
                              style={{ width: `${src.percentage}%` }}
                            />
                          </div>
                          <span className="text-sm">{src.percentage}%</span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Cross-Product Comparison */}
      {productUsage.length > 1 && (
        <>
          <Separator />
          <div>
            <h2 className="text-xl font-bold tracking-tight mb-1">
              Cross-Product Comparison
              {selectedUserId && (
                <span className="text-sm font-normal text-muted-foreground ml-2">
                  for {users.find(u => u.id === selectedUserId)?.name || selectedUserId}
                </span>
              )}
            </h2>
            <p className="text-sm text-muted-foreground mb-4">
              Token usage, requests, and cost breakdown by product
            </p>
          </div>
          <div className="grid gap-6 lg:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Tokens by Product</CardTitle>
              </CardHeader>
              <CardContent>
                <BarChart
                  data={productUsage.map((p, idx) => ({
                    id: p.productId,
                    value: p.tokens,
                    label: p.productId,
                    color: COLORS[idx % COLORS.length],
                  }))}
                  width={640}
                  height={280}
                  className="h-auto w-full"
                  ariaLabel="Tokens by product"
                />
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Product Breakdown</CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Product</TableHead>
                      <TableHead className="text-right">Tokens</TableHead>
                      <TableHead className="text-right">Requests</TableHead>
                      <TableHead className="text-right">Cost</TableHead>
                      <TableHead className="text-right">% of Tokens</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {productUsage.map((prod, idx) => (
                      <TableRow key={prod.productId}>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <div
                              className="h-3 w-3 rounded-full"
                              style={{ backgroundColor: COLORS[idx % COLORS.length] }}
                            />
                            <span className="font-medium">{prod.productId}</span>
                          </div>
                        </TableCell>
                        <TableCell className="text-right font-mono">
                          {formatNumber(prod.tokens)}
                        </TableCell>
                        <TableCell className="text-right font-mono">
                          {formatNumber(prod.requests)}
                        </TableCell>
                        <TableCell className="text-right font-mono">
                          {formatCurrency(prod.cost)}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end gap-2">
                            <div className="h-2 w-16 rounded-full bg-muted overflow-hidden">
                              <div
                                className="h-full rounded-full"
                                style={{
                                  width: `${prod.percentage}%`,
                                  backgroundColor: COLORS[idx % COLORS.length],
                                }}
                              />
                            </div>
                            <span className="text-sm">{prod.percentage}%</span>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </div>
        </>
      )}

      {/* Cohort Retention Analysis */}
      <Separator />
      <div>
        <h2 className="text-xl font-bold tracking-tight mb-1">Cohort Retention</h2>
        <p className="text-sm text-muted-foreground mb-4">
          Weekly signup cohorts — percentage of users active at 7, 14, and 30 days after signup
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Retention by Signup Week</CardTitle>
        </CardHeader>
        <CardContent>
          {cohorts.length === 0 ? (
            <p className="text-center text-muted-foreground py-8 text-sm">
              No cohort data available yet. Users need to sign up and use the platform.
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Cohort</TableHead>
                  <TableHead>Week Start</TableHead>
                  <TableHead className="text-right">Signups</TableHead>
                  <TableHead className="text-center">7-Day</TableHead>
                  <TableHead className="text-center">14-Day</TableHead>
                  <TableHead className="text-center">30-Day</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {cohorts.map(c => (
                  <TableRow key={c.cohortWeek}>
                    <TableCell className="font-mono text-sm font-medium">{c.cohortWeek}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{c.cohortStart}</TableCell>
                    <TableCell className="text-right font-mono text-sm">{c.signups}</TableCell>
                    <TableCell className="text-center">
                      <RetentionCell rate={c.rate7d} count={c.retained7d} />
                    </TableCell>
                    <TableCell className="text-center">
                      <RetentionCell rate={c.rate14d} count={c.retained14d} />
                    </TableCell>
                    <TableCell className="text-center">
                      <RetentionCell rate={c.rate30d} count={c.retained30d} />
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function RetentionCell({ rate, count }: { rate: number; count: number }) {
  if (rate < 0) {
    return <span className="text-xs text-muted-foreground">—</span>;
  }
  const bg =
    rate >= 60
      ? 'bg-emerald-100 text-emerald-800'
      : rate >= 40
        ? 'bg-emerald-50 text-emerald-700'
        : rate >= 20
          ? 'bg-amber-50 text-amber-700'
          : 'bg-red-50 text-red-700';
  return (
    <span
      className={`inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium ${bg}`}
      title={`${count} users retained`}
    >
      {rate}%
    </span>
  );
}
