'use client';

import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';

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

  const { data: queue, isLoading, error } = useQuery<Awaited<ReturnType<typeof apiClient.eresidency.getReviewQueue>>>({
    queryKey: ['review-queue'],
    queryFn: async () => {
      return await apiClient.eresidency.getReviewQueue({ limit: 50 });
    },
  });

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4">
          <Card>
            <CardContent className="py-12 text-center">
              <p className="text-gray-600">Loading review queue...</p>
            </CardContent>
          </Card>
        </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 review queue</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-red-600">{error instanceof Error ? error.message : 'Unknown error'}</p>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  const getStatusColor = (status: string): string => {
    switch (status) {
      case 'under_review':
        return 'text-blue-600 bg-blue-50';
      case 'kyc_pending':
        return 'text-yellow-600 bg-yellow-50';
      case 'approved':
        return 'text-green-600 bg-green-50';
      case 'rejected':
        return 'text-red-600 bg-red-50';
      default:
        return 'text-gray-600 bg-gray-50';
    }
  };

  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">Application Review Queue</h1>
          <p className="text-gray-600">Review and adjudicate eResidency applications</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Applications</CardTitle>
            <CardDescription>
              {queue?.total || 0} application{queue?.total !== 1 ? 's' : ''} in queue
            </CardDescription>
          </CardHeader>
          <CardContent>
            {!queue || queue.applications.length === 0 ? (
              <p className="text-gray-600 text-center py-8">No applications in queue</p>
            ) : (
              <div className="space-y-4">
                {queue.applications.map((app: { id: string; givenName: string; familyName: string; email: string; submittedAt?: string; status: string; riskScore?: number }) => (
                  <Link key={app.id} href={`/review/${app.id}`}>
                    <Card className="hover:shadow-md transition-shadow cursor-pointer">
                      <CardContent className="p-6">
                        <div className="flex items-center justify-between">
                          <div>
                            <h3 className="font-semibold text-lg">
                              {app.givenName} {app.familyName}
                            </h3>
                            <p className="text-sm text-gray-600">{app.email}</p>
                            <p className="text-xs text-gray-500 mt-1">
                              Submitted: {app.submittedAt ? new Date(app.submittedAt).toLocaleString() : 'N/A'}
                            </p>
                          </div>
                          <div className="text-right">
                            <div className={`px-3 py-1 rounded-md inline-block ${getStatusColor(app.status)}`}>
                              {app.status.toUpperCase().replace('_', ' ')}
                            </div>
                            {app.riskScore !== undefined && (
                              <p className="text-sm text-gray-600 mt-2">
                                Risk Score: {(app.riskScore * 100).toFixed(1)}%
                              </p>
                            )}
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </Link>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

