import { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { 
  IndianRupee, 
  CheckCircle, 
  Clock, 
  CreditCard,
} from 'lucide-react';
import { toast } from 'sonner';
import { onboardingService } from '@/services/onboarding.service';

interface FinanceOnboardingPageProps {
  onViewPaymentDetails?: (applicationId: string) => void;
  onViewAuditDetails?: (applicationId: string) => void;
}

export function FinanceOnboardingPage({ onViewPaymentDetails }: FinanceOnboardingPageProps = {}) {
  const [applications, setApplications] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterStatus, setFilterStatus] = useState<'all' | 'pending' | 'verified'>('pending');

  useEffect(() => {
    fetchApplications();
  }, []);

  const fetchApplications = async () => {
    try {
      setLoading(true);
      const response = await onboardingService.getApplications();
      setApplications(response.data || []);
    } catch (error) {
      console.error('Fetch error:', error);
      toast.error('Failed to fetch applications');
    } finally {
      setLoading(false);
    }
  };

  const normalizeStatus = (status: any) => String(status || '').trim().toLowerCase();
  const isVerifiedLikeStatus = (status: any) => {
    const normalized = normalizeStatus(status);
    return normalized === 'verified' || normalized === 'paid';
  };

  const paymentRows = applications.flatMap((app: any) => {
    const s = app.overallStatus || app.status;
    const isPaymentStage = [
      'Payment Pending', 'Security Details', 'LOI In Progress', 'LOI Issued',
      'LOA Pending', 'Dealer Code Generation', 'LOA_APPROVAL'
    ].includes(s);
    const deposits = app.securityDeposits || [];

    // Always include actual recorded deposits (including already verified rows)
    if (deposits.length > 0) {
      return deposits.map((d: any) => ({
        id: d.id,
        applicationId: app.applicationId || app.id,
        application: app,
        paymentStatus: d.status,
        paymentType: d.depositType,
        amount: d.amount,
        createdAt: d.createdAt,
        verificationDate: d.verifiedAt,
        isVirtual: false
      }));
    }

    // Keep virtual pending rows for in-flight cases with no deposit record yet
    if (isPaymentStage) {
      if (['Payment Pending', 'Security Details', 'LOI In Progress'].includes(s)) {
        return [{
          id: `virtual-${app.id}-sd`,
          applicationId: app.applicationId || app.id,
          application: app,
          paymentStatus: 'Pending',
          paymentType: 'SECURITY_DEPOSIT',
          amount: 500000,
          createdAt: app.updatedAt,
          verificationDate: null,
          isVirtual: true
        }];
      }
      return [{
        id: `virtual-${app.id}-ff`,
        applicationId: app.applicationId || app.id,
        application: app,
        paymentStatus: 'Pending',
        paymentType: 'FIRST_FILL',
        amount: 1500000,
        createdAt: app.updatedAt,
        verificationDate: null,
        isVirtual: true
      }];
    }

    return [];
  });

  const displayRows = paymentRows.filter((row: any) => {
    if (filterStatus === 'all') return true;
    if (filterStatus === 'pending') return !isVerifiedLikeStatus(row.paymentStatus);
    if (filterStatus === 'verified') return isVerifiedLikeStatus(row.paymentStatus);
    return true;
  });

  const handleAction = (appId: string) => {
    if (onViewPaymentDetails) {
      onViewPaymentDetails(appId);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-20 text-blue-600">
        <Clock className="w-8 h-8 animate-spin mr-3" />
        <span>Loading Finance Queue...</span>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between bg-white p-6 rounded-2xl border border-slate-100 shadow-sm">
        <div>
          <h1 className="text-3xl font-bold text-slate-900 tracking-tight mb-1">Payment Verification</h1>
          <p className="text-slate-500">Review and verify dealer security deposits and first fill payments</p>
        </div>
        <div className="flex items-center gap-3">
           <Button onClick={fetchApplications} variant="outline" size="sm" className="bg-white hover:bg-slate-50" data-testid="onboarding-finance-queue-sync-btn">
            <Clock className="w-4 h-4 mr-2" />
            Sync Dashboard
          </Button>
        </div>
      </div>

      {/* Mode Switcher - Simplified */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div className="inline-flex p-1 bg-slate-100 rounded-xl">
          <div className="flex items-center px-4 py-2 bg-white rounded-lg text-slate-900 shadow-sm font-medium text-sm" data-testid="onboarding-finance-queue-pending-count">
            <IndianRupee className="w-4 h-4 mr-2 text-blue-600" />
            Pending Payments ({paymentRows.filter((row: any) => !isVerifiedLikeStatus(row.paymentStatus)).length})
          </div>
        </div>

        <div className="flex gap-2">
          <Button
            variant={filterStatus === 'pending' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setFilterStatus('pending')}
            className={filterStatus === 'pending' ? 'bg-slate-200 text-slate-900' : 'text-slate-500'}
            data-testid="onboarding-finance-queue-filter-pending"
          >
            Pending
          </Button>
          <Button
            variant={filterStatus === 'verified' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setFilterStatus('verified')}
            className={filterStatus === 'verified' ? 'bg-slate-200 text-slate-900' : 'text-slate-500'}
            data-testid="onboarding-finance-queue-filter-verified"
          >
            Verified
          </Button>
          <Button
            variant={filterStatus === 'all' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setFilterStatus('all')}
            className={filterStatus === 'all' ? 'bg-slate-200 text-slate-900' : 'text-slate-500'}
            data-testid="onboarding-finance-queue-filter-all"
          >
            All
          </Button>
        </div>
      </div>

      {/* Applications Table */}
      <Card className="border-none shadow-xl overflow-hidden rounded-2xl bg-white" data-testid="onboarding-finance-queue-table-card">
        <CardContent className="p-0">
          <Table>
            <TableHeader className="bg-slate-50/50">
              <TableRow className="border-b border-slate-100 uppercase text-[10px] tracking-wider font-bold text-slate-400">
                <TableHead className="py-4 pl-6" data-testid="onboarding-finance-queue-th-details">Application Details</TableHead>
                <TableHead data-testid="onboarding-finance-queue-th-location">Location</TableHead>
                <TableHead data-testid="onboarding-finance-queue-th-stage">Payment Stage</TableHead>
                <TableHead data-testid="onboarding-finance-queue-th-status">Current Status</TableHead>
                <TableHead className="text-right pr-6" data-testid="onboarding-finance-queue-th-action">Workflow Action</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {displayRows.length > 0 ? (
                displayRows.map((row: any, idx: number) => {
                  const statusLabel = row.paymentStatus || 'Awaiting Payment';
                  const app = row.application || {};
                  return (
                    <TableRow key={row.id} className="hover:bg-blue-50/20 group transition-all" data-testid={`onboarding-finance-queue-row-${idx}`}>
                      <TableCell className="py-4 pl-6">
                        <div className="flex flex-col">
                          <span className="font-mono text-xs font-bold text-blue-600 mb-1" data-testid={`onboarding-finance-queue-app-id-${idx}`}>{app.applicationId || app.id}</span>
                          <div className="flex items-center gap-2">
                            <span className="font-semibold text-slate-900" data-testid={`onboarding-finance-queue-name-${idx}`}>{app.applicantName}</span>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-col text-sm" data-testid={`onboarding-finance-queue-location-${idx}`}>
                          <span className="text-slate-600 leading-none">{app.city}</span>
                          <span className="text-slate-400 text-xs mt-1">{app.state}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                         <div className="flex items-center gap-2" data-testid={`onboarding-finance-queue-type-${idx}`}>
                           <CreditCard className="w-4 h-4 text-slate-400" />
                           <span className="text-sm font-medium">
                             {row.paymentType === 'SECURITY_DEPOSIT' ? 'Security Deposit (₹5L)' : 'First Fill (₹15L)'}
                           </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          className={
                            statusLabel === 'Verified' ? 'bg-emerald-50 text-emerald-700 border-emerald-100 px-3 py-1 rounded-full' :
                            statusLabel === 'Rejected' ? 'bg-rose-50 text-rose-700 border-rose-100 px-3 py-1 rounded-full' :
                            'bg-amber-50 text-amber-700 border-amber-100 px-3 py-1 rounded-full'
                          }
                          variant="outline"
                          data-testid={`onboarding-finance-queue-status-${idx}`}
                        >
                          {statusLabel}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right pr-6">
                        <Button 
                          size="sm" 
                          variant={isVerifiedLikeStatus(statusLabel) ? 'outline' : 'default'}
                          className={!isVerifiedLikeStatus(statusLabel)
                            ? 'bg-blue-600 hover:bg-blue-700 shadow-md' 
                            : 'bg-white text-slate-600 border-slate-200'}
                          onClick={() => handleAction(row.applicationId || app.id)}
                          data-testid={`onboarding-finance-queue-action-btn-${idx}`}
                        >
                            <>
                                                <IndianRupee className="w-4 h-4 mr-2" />
                              {isVerifiedLikeStatus(statusLabel) ? 'View Receipt' : 'Record Payment'}
                            </>
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow>
                  <TableCell colSpan={5} className="h-48 text-center text-slate-400 py-10" data-testid="onboarding-finance-queue-empty">
                    <div className="flex flex-col items-center gap-3">
                      <div className="w-12 h-12 bg-slate-50 rounded-full flex items-center justify-center">
                        <CheckCircle className="w-6 h-6 text-slate-200" />
                      </div>
                      <p className="text-sm">
                        {filterStatus === 'verified'
                          ? 'No verified payments found'
                          : filterStatus === 'pending'
                            ? 'No pending payments in the queue'
                            : 'No onboarding payments found'}
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
