'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  ArrowLeft,
  User,
  Mail,
  Calendar,
  Activity,
  Zap,
  DollarSign,
  Shield,
  Clock,
  BarChart3,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { apiGetUserView, type UserViewResponse, type ApiUsageRecord } from '@/lib/api';
import { formatNumber, formatCurrency, formatDate } from '@/lib/mock-data';
import { AreaChart } from '@/components/charts';
import { seriesValues } from '@/lib/chart-data';

const planColors: Record<string, string> = {
  free: '',
  pro: 'bg-blue-50 text-blue-700',
  enterprise: 'bg-violet-50 text-violet-700',
};

const statusColors: Record<string, string> = {
  active: 'bg-emerald-50 text-emerald-700',
  inactive: 'bg-amber-50 text-amber-700',
  suspended: 'bg-red-50 text-red-700',
};

interface DailyUsage {
  date: string;
  dictations: number;
  words: number;
  tokens: number;
  cost: number;
}

function aggregateDaily(records: ApiUsageRecord[]): DailyUsage[] {
  const byDate = new Map<string, DailyUsage>();
  for (const r of records) {
    const existing = byDate.get(r.date);
    if (existing) {
      existing.dictations += r.dictations;
      existing.words += r.words;
      existing.tokens += r.tokensUsed;
      existing.cost += r.costUsd;
    } else {
      byDate.set(r.date, {
        date: r.date,
        dictations: r.dictations,
        words: r.words,
        tokens: r.tokensUsed,
        cost: r.costUsd,
      });
    }
  }
  return Array.from(byDate.values()).sort((a, b) => a.date.localeCompare(b.date));
}

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-8 w-48" />
      <div className="grid gap-4 md:grid-cols-4">
        {[1, 2, 3, 4].map(i => (
          <Skeleton key={i} className="h-24" />
        ))}
      </div>
      <Skeleton className="h-[300px]" />
    </div>
  );
}

export default function UserDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [data, setData] = useState<UserViewResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) return;
    apiGetUserView(id)
      .then(({ data: viewData, error: err }) => {
        if (err) setError(err);
        else if (viewData) setData(viewData);
      })
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) return <LoadingSkeleton />;

  if (error || !data) {
    return (
      <div className="space-y-4">
        <Button variant="ghost" onClick={() => router.push('/users')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Users
        </Button>
        <Card>
          <CardContent className="pt-6 text-center text-muted-foreground">
            {error || 'User not found'}
          </CardContent>
        </Card>
      </div>
    );
  }

  const { profile, usage } = data;
  const records = usage?.records ?? [];
  const dailyUsage = aggregateDaily(records);
  const totalTokens = records.reduce((s, r) => s + r.tokensUsed, 0);
  const totalWords = records.reduce((s, r) => s + r.words, 0);
  const totalDictations = records.reduce((s, r) => s + r.dictations, 0);
  const totalCost = records.reduce((s, r) => s + r.costUsd, 0);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.push('/users')}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold">{profile.name}</h1>
              <Badge variant="secondary" className={planColors[profile.plan] || ''}>
                {profile.plan}
              </Badge>
              <Badge variant="secondary" className={statusColors[profile.status] || ''}>
                {profile.status}
              </Badge>
            </div>
            <p className="text-muted-foreground text-sm">{profile.email}</p>
          </div>
        </div>
        <Badge variant="outline" className="text-xs">
          <Shield className="mr-1 h-3 w-3" />
          Read-only view
        </Badge>
      </div>

      {/* Impersonation Banner */}
      <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 flex items-center gap-2">
        <Shield className="h-4 w-4 shrink-0" />
        <span>
          You are viewing this user&apos;s data as <strong>{data.viewedBy.name}</strong> (
          {data.viewedBy.role}). All data is read-only.
        </span>
      </div>

      {/* Profile Info */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
              <User className="h-3.5 w-3.5" /> User ID
            </CardTitle>
          </CardHeader>
          <CardContent>
            <code className="text-xs font-mono">{profile.id}</code>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
              <Mail className="h-3.5 w-3.5" /> Email
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm font-medium">{profile.email}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
              <Calendar className="h-3.5 w-3.5" /> Member Since
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm font-medium">{formatDate(profile.createdAt)}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
              <Clock className="h-3.5 w-3.5" /> Last Active
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm font-medium">{formatDate(profile.lastActive)}</p>
          </CardContent>
        </Card>
      </div>

      {/* Usage KPI Cards (30 days) */}
      <div>
        <h2 className="text-lg font-semibold mb-3">Usage (Last 30 Days)</h2>
        <div className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <Activity className="h-3.5 w-3.5" /> Dictations
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{formatNumber(totalDictations)}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <BarChart3 className="h-3.5 w-3.5" /> Words
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{formatNumber(totalWords)}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <Zap className="h-3.5 w-3.5" /> Tokens Used
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{formatNumber(totalTokens)}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-1">
                <DollarSign className="h-3.5 w-3.5" /> Cost
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{formatCurrency(totalCost)}</p>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Usage Chart */}
      {dailyUsage.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Daily Dictation Activity</CardTitle>
          </CardHeader>
          <CardContent>
            <AreaChart
              values={seriesValues(dailyUsage, 'dictations')}
              width={720}
              height={250}
              className="h-auto w-full"
              ariaLabel="Daily dictation activity"
            />
          </CardContent>
        </Card>
      )}

      {/* Recent Usage Records Table */}
      {records.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Recent Usage Records ({records.length})</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Date</TableHead>
                  <TableHead className="text-right">Dictations</TableHead>
                  <TableHead className="text-right">Words</TableHead>
                  <TableHead className="text-right">Tokens</TableHead>
                  <TableHead className="text-right">Cost</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {records.slice(0, 20).map(r => (
                  <TableRow key={r.id}>
                    <TableCell className="text-sm">{r.date}</TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(r.dictations)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(r.words)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(r.tokensUsed)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatCurrency(r.costUsd)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {records.length === 0 && (
        <Card>
          <CardContent className="pt-6 text-center text-muted-foreground">
            <Activity className="mx-auto h-10 w-10 mb-3 opacity-30" />
            <p className="text-sm">No usage data in the last 30 days</p>
          </CardContent>
        </Card>
      )}

      <Separator />

      {/* Lifetime Stats */}
      <div>
        <h2 className="text-lg font-semibold mb-3">Lifetime Statistics</h2>
        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">Total Tokens Used</p>
              <p className="text-xl font-bold font-mono">{formatNumber(profile.totalTokensUsed)}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">Total Requests</p>
              <p className="text-xl font-bold font-mono">{formatNumber(profile.totalRequests)}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">Monthly Spend</p>
              <p className="text-xl font-bold font-mono">{formatCurrency(profile.monthlySpend)}</p>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
