'use client';

import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Badge, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';

export default function MetricsPage(): JSX.Element {
  const apiClient = getApiClient();

  const { data: dashboard, isLoading, error } = useQuery<Awaited<ReturnType<typeof apiClient.identity.getMetricsDashboard>>>({
    queryKey: ['metrics-dashboard'],
    queryFn: async () => {
      return await apiClient.identity.getMetricsDashboard();
    },
  });

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4">
          <div className="mb-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-2">Metrics & Analytics</h1>
            <p className="text-gray-600">Credential issuance metrics and analytics</p>
          </div>
          <div className="grid md:grid-cols-4 gap-6">
            {[1, 2, 3, 4].map((i) => (
              <Card key={i}>
                <CardContent className="p-6">
                  <Skeleton className="h-8 w-24 mb-2" />
                  <Skeleton className="h-4 w-32" />
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4">
          <Card>
            <CardHeader>
              <CardTitle>Error</CardTitle>
              <CardDescription>Failed to load metrics</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-red-600">{error instanceof Error ? error.message : 'Unknown error'}</p>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  const summary = dashboard?.summary;

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Metrics & Analytics</h1>
          <p className="text-gray-600">Credential issuance metrics and analytics</p>
        </div>

        <div className="grid md:grid-cols-4 gap-6 mb-8">
          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium text-gray-500">Issued Today</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{summary?.issuedToday || 0}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium text-gray-500">Issued This Week</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{summary?.issuedThisWeek || 0}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium text-gray-500">Issued This Month</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{summary?.issuedThisMonth || 0}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-sm font-medium text-gray-500">Success Rate</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold">{summary?.successRate ? summary.successRate.toFixed(1) : 0}%</div>
            </CardContent>
          </Card>
        </div>

        <div className="grid md:grid-cols-2 gap-6 mb-8">
          <Card>
            <CardHeader>
              <CardTitle>Top Credential Types</CardTitle>
              <CardDescription>Most issued credential types</CardDescription>
            </CardHeader>
            <CardContent>
              {dashboard?.topCredentialTypes && dashboard.topCredentialTypes.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Type</TableHead>
                      <TableHead>Count</TableHead>
                      <TableHead>Percentage</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {dashboard.topCredentialTypes.map((item: { type: string; count: number; percentage: number }) => (
                      <TableRow key={item.type}>
                        <TableCell>{item.type}</TableCell>
                        <TableCell>{item.count}</TableCell>
                        <TableCell>{item.percentage.toFixed(1)}%</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <p className="text-gray-600 text-center py-4">No data available</p>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Recent Issuances</CardTitle>
              <CardDescription>Latest credential issuances</CardDescription>
            </CardHeader>
            <CardContent>
              {summary?.recentIssuances && summary.recentIssuances.length > 0 ? (
                <div className="space-y-4">
                  {summary.recentIssuances.map((issuance: { credentialId: string; credentialType: string[]; issuedAt: Date; subjectDid: string }) => (
                    <div key={issuance.credentialId} className="flex items-center justify-between border-b pb-3">
                      <div>
                        <p className="font-medium">{issuance.credentialType.join(', ')}</p>
                        <p className="text-sm text-gray-600">{issuance.credentialId}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-600">
                          {new Date(issuance.issuedAt).toLocaleDateString()}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-600 text-center py-4">No recent issuances</p>
              )}
            </CardContent>
          </Card>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Credential Type Distribution</CardTitle>
            <CardDescription>Breakdown by credential type</CardDescription>
          </CardHeader>
          <CardContent>
            {summary?.byCredentialType && Object.keys(summary.byCredentialType).length > 0 ? (
              <div className="space-y-2">
                {Object.entries(summary.byCredentialType).map(([type, count]: [string, number]) => (
                  <div key={type} className="flex items-center justify-between">
                    <span className="text-sm font-medium">{type}</span>
                    <Badge>{count}</Badge>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-gray-600 text-center py-4">No data available</p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

