'use client';

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

export default function CredentialsPage(): JSX.Element {
  const router = useRouter();
  const apiClient = getApiClient();
  const [searchTerm, setSearchTerm] = useState('');

  // This would typically fetch from an endpoint that lists credentials
  // For now, we'll use a placeholder query
  const { data: metrics, isLoading } = useQuery({
    queryKey: ['credentials-list'],
    queryFn: async () => {
      // Placeholder - in production, this would be a dedicated endpoint
      const dashboard = await apiClient.identity.getMetricsDashboard();
      return dashboard.summary.recentIssuances;
    },
  });

  const filteredData = metrics?.filter((item: { credentialId: string; credentialType: string[] }) =>
    item.credentialId.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.credentialType.some((type: string) => type.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4">
          <div className="mb-8 flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 mb-2">Credential Management</h1>
              <p className="text-gray-600">Manage and view verifiable credentials</p>
            </div>
            <Button onClick={() => router.push('/credentials/issue')}>Issue New Credential</Button>
          </div>

        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>Credentials</CardTitle>
                <CardDescription>View and manage issued credentials</CardDescription>
              </div>
              <div className="w-64">
                <Input
                  placeholder="Search credentials..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : filteredData && filteredData.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Credential ID</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Subject DID</TableHead>
                    <TableHead>Issued At</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredData.map((credential: { credentialId: string; credentialType: string[]; issuedAt: Date; subjectDid: string }) => (
                    <TableRow key={credential.credentialId}>
                      <TableCell className="font-mono text-sm">{credential.credentialId}</TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {credential.credentialType.map((type: string) => (
                            <Badge key={type} variant="secondary">
                              {type}
                            </Badge>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell className="font-mono text-sm">{credential.subjectDid}</TableCell>
                      <TableCell>{new Date(credential.issuedAt).toLocaleString()}</TableCell>
                      <TableCell>
                        <Badge variant="success">Active</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button variant="outline" size="sm">
                            View
                          </Button>
                          <Button variant="destructive" size="sm">
                            Revoke
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <p className="text-center text-gray-600 py-8">No credentials found</p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

