'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Button, Badge, Alert, AlertDescription, Textarea, Label, useToast } from '@the-order/ui';
import { getApiClient } from '@the-order/api-client';
import { useState } from 'react';

export default function ReviewDetailPage(): JSX.Element {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const apiClient = getApiClient();
  const applicationId = params.id as string;
  const [decision, setDecision] = useState<'approve' | 'reject' | null>(null);
  const [notes, setNotes] = useState('');
  const [reason, setReason] = useState('');
  const { success, error: showError } = useToast();

  const { data: application, isLoading, error } = useQuery<Awaited<ReturnType<typeof apiClient.eresidency.getApplicationForReview>>>({
    queryKey: ['application', applicationId],
    queryFn: async () => {
      return await apiClient.eresidency.getApplicationForReview(applicationId);
    },
  });

  const adjudicateMutation = useMutation<Awaited<ReturnType<typeof apiClient.eresidency.adjudicateApplication>>, Error, { decision: 'approve' | 'reject'; reason?: string; notes?: string }>({
    mutationFn: async (data: { decision: 'approve' | 'reject'; reason?: string; notes?: string }) => {
      return await apiClient.eresidency.adjudicateApplication(applicationId, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['application', applicationId] });
      queryClient.invalidateQueries({ queryKey: ['review-queue'] });
      success('Decision submitted successfully', 'The application has been adjudicated.');
      router.push('/review');
    },
    onError: (error) => {
      showError(
        error instanceof Error ? error.message : 'Failed to submit decision',
        'Error'
      );
    },
  });

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4 max-w-4xl">
          <Card>
            <CardContent className="py-12 text-center">
              <p className="text-gray-600">Loading application...</p>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (error || !application) {
    return (
      <div className="min-h-screen bg-gray-50 py-12">
        <div className="container mx-auto px-4 max-w-4xl">
          <Card>
            <CardHeader>
              <CardTitle>Error</CardTitle>
              <CardDescription>Failed to load application</CardDescription>
            </CardHeader>
            <CardContent>
              <p className="text-red-600">{error instanceof Error ? error.message : 'Application not found'}</p>
              <Button onClick={() => router.push('/review')} className="mt-4">
                Back to Queue
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  const getStatusBadge = (status: string): JSX.Element => {
    switch (status) {
      case 'approved':
        return <Badge variant="success">Approved</Badge>;
      case 'rejected':
        return <Badge variant="destructive">Rejected</Badge>;
      case 'under_review':
        return <Badge variant="default">Under Review</Badge>;
      case 'kyc_pending':
        return <Badge variant="warning">KYC Pending</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const handleAdjudicate = (): void => {
    if (!decision) return;
    if (decision === 'reject' && !reason.trim()) {
      alert('Please provide a rejection reason');
      return;
    }
    adjudicateMutation.mutate({
      decision,
      reason: decision === 'reject' ? reason : undefined,
      notes: notes.trim() || undefined,
    });
  };

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="container mx-auto px-4 max-w-4xl">
        <div className="mb-6">
          <Button variant="outline" onClick={() => router.push('/review')}>
            ← Back to Queue
          </Button>
        </div>

        <div className="grid gap-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>
                    {application.givenName} {application.familyName}
                  </CardTitle>
                  <CardDescription>Application ID: {application.id}</CardDescription>
                </div>
                {getStatusBadge(application.status)}
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid md:grid-cols-2 gap-6">
                <div>
                  <Label className="text-sm font-medium text-gray-500">Email</Label>
                  <p className="mt-1 text-gray-900">{application.email}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">Phone</Label>
                  <p className="mt-1 text-gray-900">{application.phone || 'N/A'}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">Date of Birth</Label>
                  <p className="mt-1 text-gray-900">{application.dateOfBirth || 'N/A'}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">Nationality</Label>
                  <p className="mt-1 text-gray-900">{application.nationality || 'N/A'}</p>
                </div>
              </div>

              {application.address && (
                <div>
                  <Label className="text-sm font-medium text-gray-500">Address</Label>
                  <p className="mt-1 text-gray-900">
                    {[
                      application.address.street,
                      application.address.city,
                      application.address.region,
                      application.address.postalCode,
                      application.address.country,
                    ]
                      .filter(Boolean)
                      .join(', ')}
                  </p>
                </div>
              )}

              {application.riskScore !== undefined && (
                <div>
                  <Label className="text-sm font-medium text-gray-500">Risk Score</Label>
                  <p className="mt-1 text-gray-900">{(application.riskScore * 100).toFixed(1)}%</p>
                </div>
              )}

              {application.kycStatus && (
                <div>
                  <Label className="text-sm font-medium text-gray-500">KYC Status</Label>
                  <p className="mt-1 text-gray-900">{application.kycStatus}</p>
                </div>
              )}

              {application.sanctionsStatus && (
                <div>
                  <Label className="text-sm font-medium text-gray-500">Sanctions Status</Label>
                  <p className="mt-1 text-gray-900">{application.sanctionsStatus}</p>
                </div>
              )}

              {application.submittedAt && (
                <div>
                  <Label className="text-sm font-medium text-gray-500">Submitted At</Label>
                  <p className="mt-1 text-gray-900">{new Date(application.submittedAt).toLocaleString()}</p>
                </div>
              )}
            </CardContent>
          </Card>

          {application.status === 'under_review' && (
            <Card>
              <CardHeader>
                <CardTitle>Adjudication</CardTitle>
                <CardDescription>Review and make a decision on this application</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex gap-4">
                  <Button
                    variant={decision === 'approve' ? 'default' : 'outline'}
                    onClick={() => setDecision('approve')}
                  >
                    Approve
                  </Button>
                  <Button
                    variant={decision === 'reject' ? 'destructive' : 'outline'}
                    onClick={() => setDecision('reject')}
                  >
                    Reject
                  </Button>
                </div>

                {decision === 'reject' && (
                  <div>
                    <Label htmlFor="reason">Rejection Reason *</Label>
                    <Textarea
                      id="reason"
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      placeholder="Please provide a reason for rejection..."
                      className="mt-2"
                      rows={3}
                    />
                  </div>
                )}

                <div>
                  <Label htmlFor="notes">Notes (Optional)</Label>
                  <Textarea
                    id="notes"
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    placeholder="Additional notes about this application..."
                    className="mt-2"
                    rows={3}
                  />
                </div>


                <div className="flex justify-end gap-4">
                  <Button variant="outline" onClick={() => router.push('/review')}>
                    Cancel
                  </Button>
                  <Button
                    onClick={handleAdjudicate}
                    disabled={adjudicateMutation.isPending || !decision || (decision === 'reject' && !reason.trim())}
                  >
                    {adjudicateMutation.isPending ? 'Submitting...' : 'Submit Decision'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {application.rejectionReason && (
            <Alert variant="destructive">
              <AlertDescription>
                <strong>Rejection Reason:</strong> {application.rejectionReason}
              </AlertDescription>
            </Alert>
          )}
        </div>
      </div>
    </div>
  );
}

