import { useEffect, useState, useMemo } from 'react';
import { Shield, Clock, FileText, ChartColumn, ChartPie, Activity, Target, DollarSign, Zap, Package, TrendingUp, TrendingDown, CircleCheckBig, CircleX, CreditCard, TriangleAlert } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { getDealerDashboard, type DashboardKPIs as DashboardKPIsType, type CategoryData as CategoryDataType } from '@/services/dealerClaimApi';
import { RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

// Use types from dealerClaimApi
type DashboardKPIs = DashboardKPIsType;
type CategoryData = CategoryDataType;

interface DashboardProps {
  onNavigate?: (page: string) => void;
  onNewRequest?: () => void;
}

export function DealerDashboard({ onNavigate, onNewRequest: _onNewRequest }: DashboardProps) {
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [kpis, setKpis] = useState<DashboardKPIs>({
    totalClaims: 0,
    totalValue: 0,
    approved: 0,
    rejected: 0,
    pending: 0,
    credited: 0,
    pendingCredit: 0,
    approvedValue: 0,
    rejectedValue: 0,
    pendingValue: 0,
    creditedValue: 0,
    pendingCreditValue: 0,
  });
  const [categoryData, setCategoryData] = useState<CategoryData[]>([]);
  const [dateRange, _setDateRange] = useState<string>('all');
  const [startDate, _setStartDate] = useState<string | undefined>();
  const [endDate, _setEndDate] = useState<string | undefined>();

  const fetchDashboardData = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }

      // Fetch dealer claims dashboard data
      const data = await getDealerDashboard(
        dateRange || 'all',
        startDate,
        endDate
      );
      
      setKpis(data.kpis || {
        totalClaims: 0,
        totalValue: 0,
        approved: 0,
        rejected: 0,
        pending: 0,
        credited: 0,
        pendingCredit: 0,
        approvedValue: 0,
        rejectedValue: 0,
        pendingValue: 0,
        creditedValue: 0,
        pendingCreditValue: 0,
      });

      setCategoryData(data.categoryData || []);
    } catch (error: any) {
      console.error('[DealerDashboard] Error fetching data:', error);
      toast.error('Failed to load dashboard data. Please try again later.');
      // Reset to empty state on error
      setKpis({
        totalClaims: 0,
        totalValue: 0,
        approved: 0,
        rejected: 0,
        pending: 0,
        credited: 0,
        pendingCredit: 0,
        approvedValue: 0,
        rejectedValue: 0,
        pendingValue: 0,
        creditedValue: 0,
        pendingCreditValue: 0,
      });
      setCategoryData([]);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const formatCurrency = (amount: number, showExactRupees = false) => {
    // Handle null, undefined, or invalid values
    if (amount == null || isNaN(amount)) {
      return '₹0';
    }
    
    // Convert to number if it's a string
    const numAmount = typeof amount === 'string' ? parseFloat(amount) : Number(amount);
    
    // Handle zero or negative values
    if (numAmount <= 0) {
      return '₹0';
    }
    
    // If showExactRupees is true or amount is less than 10,000, show exact rupees
    if (showExactRupees || numAmount < 10000) {
      return `₹${Math.round(numAmount).toLocaleString('en-IN')}`;
    }
    
    if (numAmount >= 100000) {
      return `₹${(numAmount / 100000).toFixed(1)}L`;
    }
    if (numAmount >= 1000) {
      return `₹${(numAmount / 1000).toFixed(1)}K`;
    }
    // Show exact rupee amount for amounts less than 1000 (e.g., ₹100, ₹200, ₹999)
    return `₹${Math.round(numAmount).toLocaleString('en-IN')}`;
  };

  const formatNumber = (num: number) => {
    return num.toLocaleString('en-IN');
  };

  const calculateApprovalRate = () => {
    if (kpis.totalClaims === 0) return 0;
    return ((kpis.approved / kpis.totalClaims) * 100).toFixed(1);
  };

  const calculateCreditRate = () => {
    if (kpis.approved === 0) return 0;
    return ((kpis.credited / kpis.approved) * 100).toFixed(1);
  };

  // Prepare data for pie chart (Distribution by Activity Type)
  const distributionData = useMemo(() => {
    const totalRaised = categoryData.reduce((sum, cat) => sum + cat.raised, 0);
    if (totalRaised === 0) return [];

    return categoryData.map(cat => ({
      name: cat.activityType.length > 20 ? cat.activityType.substring(0, 20) + '...' : cat.activityType,
      value: cat.raised,
      fullName: cat.activityType,
      percentage: ((cat.raised / totalRaised) * 100).toFixed(0),
    }));
  }, [categoryData]);

  // Prepare data for bar chart (Status by Category)
  const statusByCategoryData = useMemo(() => {
    return categoryData.map(cat => ({
      name: cat.activityType.length > 15 ? cat.activityType.substring(0, 15) + '...' : cat.activityType,
      fullName: cat.activityType,
      Raised: cat.raised,
      Approved: cat.approved,
      Rejected: cat.rejected,
      Pending: cat.pending,
    }));
  }, [categoryData]);

  // Prepare data for value comparison chart (keep original values, formatCurrency will handle display)
  const valueComparisonData = useMemo(() => {
    return categoryData.map(cat => ({
      name: cat.activityType.length > 15 ? cat.activityType.substring(0, 15) + '...' : cat.activityType,
      fullName: cat.activityType,
      Raised: cat.raisedValue, // Keep original value
      Approved: cat.approvedValue, // Keep original value
      Credited: cat.creditedValue, // Keep original value
    }));
  }, [categoryData]);

  const COLORS = ['#166534', '#15803d', '#16a34a', '#22c55e', '#4ade80', '#86efac', '#bbf7d0'];

  // Find best performing category
  const bestPerforming = useMemo(() => {
    if (categoryData.length === 0) return null;
    return categoryData.reduce((best, cat) => 
      cat.approvalRate > (best?.approvalRate || 0) ? cat : best
    );
  }, [categoryData]);

  // Find highest value category
  const highestValue = useMemo(() => {
    if (categoryData.length === 0) return null;
    return categoryData.reduce((best, cat) => 
      cat.raisedValue > (best?.raisedValue || 0) ? cat : best
    );
  }, [categoryData]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="flex flex-col items-center gap-4">
          <RefreshCw className="w-8 h-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">Loading dashboard...</p>
        </div>
      </div>
    );
  }

  // Show empty state if no data
  const hasNoData = kpis.totalClaims === 0 && categoryData.length === 0;

  if (hasNoData) {
    return (
      <div className="space-y-6 max-w-[1600px] mx-auto p-4">
        {/* Hero Section */}
        <Card className="border-0 shadow-xl relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900" />
          <CardContent className="relative z-10 p-8 lg:p-12">
            <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
              <div className="text-white">
                <div className="flex items-center gap-4 mb-6">
                  <div className="w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg">
                    <Shield className="w-8 h-8 text-slate-900" />
                  </div>
                  <div>
                    <h1 className="text-4xl text-white font-bold">Claims Analytics Dashboard</h1>
                    <p className="text-xl text-gray-200 mt-1">Comprehensive insights into approval workflows</p>
                  </div>
                </div>
                <div className="flex flex-wrap gap-4 mt-8">
                  <Button
                    onClick={() => {
                      setRefreshing(true);
                      fetchDashboardData(true);
                    }}
                    disabled={refreshing}
                    variant="outline"
                    className="bg-white/10 hover:bg-white/20 text-white border-white/20"
                  >
                    <RefreshCw className={`w-5 h-5 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
                    Refresh
                  </Button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Empty State */}
        <Card className="shadow-lg">
          <CardContent className="flex flex-col items-center justify-center py-16 px-4">
            <div className="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-6">
              <ChartPie className="w-12 h-12 text-gray-400" />
            </div>
            <h2 className="text-2xl font-semibold text-gray-900 mb-2">No Claims Data Available</h2>
            <p className="text-gray-600 text-center max-w-md mb-6">
              You don't have any claims data yet. Once you create and submit claim requests, your analytics will appear here.
            </p>
            <div className="flex flex-col sm:flex-row gap-4">
              <Button
                onClick={() => {
                  setRefreshing(true);
                  fetchDashboardData(true);
                }}
                disabled={refreshing}
                variant="outline"
              >
                <RefreshCw className={`w-5 h-5 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
                Refresh Data
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-[1600px] mx-auto p-4">
      {/* Hero Section */}
      <Card className="border-0 shadow-xl relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900" />
        <CardContent className="relative z-10 p-8 lg:p-12">
          <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
            <div className="text-white">
              <div className="flex items-center gap-4 mb-6">
                <div className="w-16 h-16 bg-yellow-400 rounded-xl flex items-center justify-center shadow-lg">
                  <Shield className="w-8 h-8 text-slate-900" />
                </div>
                <div>
                  <h1 className="text-4xl text-white font-bold">Claims Analytics Dashboard</h1>
                  <p className="text-xl text-gray-200 mt-1">Comprehensive insights into approval workflows</p>
                </div>
              </div>
              <div className="flex flex-wrap gap-4 mt-8">
                <Button
                  onClick={() => onNavigate?.('/requests?status=pending')}
                  className="bg-blue-600 hover:bg-blue-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200"
                >
                  <Clock className="w-5 h-5 mr-2" />
                  View Pending Claims
                </Button>
                <Button
                  onClick={() => onNavigate?.('/requests')}
                  className="bg-emerald-600 hover:bg-emerald-700 text-white border-0 shadow-lg hover:shadow-xl transition-all duration-200"
                >
                  <FileText className="w-5 h-5 mr-2" />
                  My Claims
                </Button>
              </div>
            </div>
            <div className="hidden lg:flex items-center gap-4">
              <div className="w-24 h-24 bg-yellow-400/20 rounded-full flex items-center justify-center">
                <div className="w-16 h-16 bg-yellow-400/30 rounded-full flex items-center justify-center">
                  <ChartColumn className="w-8 h-8 text-yellow-400" />
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4">
        <Card className="border-l-4 border-l-blue-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Raised Claims</CardTitle>
              <div className="p-2 rounded-lg bg-blue-50">
                <FileText className="h-4 w-4 text-blue-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.totalClaims)}</div>
            <p className="text-xs text-muted-foreground mt-1">{formatCurrency(kpis.totalValue, true)}</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-green-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Approved</CardTitle>
              <div className="p-2 rounded-lg bg-green-50">
                <CircleCheckBig className="h-4 w-4 text-green-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.approved)}</div>
            <div className="flex items-center gap-1 mt-1">
              <TrendingUp className="h-3 w-3 text-green-600" />
              <p className="text-xs text-green-600">{calculateApprovalRate()}% approval rate</p>
            </div>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-red-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Rejected</CardTitle>
              <div className="p-2 rounded-lg bg-red-50">
                <CircleX className="h-4 w-4 text-red-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.rejected)}</div>
            <div className="flex items-center gap-1 mt-1">
              <TrendingDown className="h-3 w-3 text-red-600" />
              <p className="text-xs text-red-600">
                {kpis.totalClaims > 0 ? ((kpis.rejected / kpis.totalClaims) * 100).toFixed(1) : 0}% rejection rate
              </p>
            </div>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-orange-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Pending</CardTitle>
              <div className="p-2 rounded-lg bg-orange-50">
                <Clock className="h-4 w-4 text-orange-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.pending)}</div>
            <p className="text-xs text-muted-foreground mt-1">{formatCurrency(kpis.pendingValue)}</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-emerald-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Credited</CardTitle>
              <div className="p-2 rounded-lg bg-emerald-50">
                <CreditCard className="h-4 w-4 text-emerald-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.credited)}</div>
            <div className="flex items-center gap-1 mt-1">
              <TrendingUp className="h-3 w-3 text-emerald-600" />
              <p className="text-xs text-emerald-600">{calculateCreditRate()}% credit rate</p>
            </div>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-amber-500 shadow-lg hover:shadow-xl transition-all duration-300">
          <CardHeader className="pb-2">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm text-muted-foreground">Pending Credit</CardTitle>
              <div className="p-2 rounded-lg bg-amber-50">
                <TriangleAlert className="h-4 w-4 text-amber-600" />
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl text-gray-900">{formatNumber(kpis.pendingCredit)}</div>
            <p className="text-xs text-muted-foreground mt-1">{formatCurrency(kpis.pendingCreditValue)}</p>
          </CardContent>
        </Card>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Distribution by Activity Type */}
        <Card className="shadow-lg">
          <CardHeader>
            <div className="flex items-center gap-3">
              <div className="p-3 bg-purple-100 rounded-lg">
                <ChartPie className="h-5 w-5 text-purple-600" />
              </div>
              <div>
                <CardTitle>Claims Distribution by Activity Type</CardTitle>
                <CardDescription>Total claims raised across activity types</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={distributionData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percentage }) => `${name}: ${percentage}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {distributionData.map((_entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
            <div className="grid grid-cols-3 gap-2 mt-4">
              {distributionData.slice(0, 3).map((item, index) => (
                <div key={index} className="flex items-center gap-2 p-2 rounded-lg bg-gray-50">
                  <div className="w-3 h-3 rounded" style={{ backgroundColor: COLORS[index % COLORS.length] }} />
                  <div>
                    <p className="text-xs text-gray-600">{item.name}</p>
                    <p className="text-sm text-gray-900">{formatNumber(item.value)}</p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Status by Category */}
        <Card className="shadow-lg">
          <CardHeader>
            <div className="flex items-center gap-3">
              <div className="p-3 bg-blue-100 rounded-lg">
                <ChartColumn className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <CardTitle>Claims Status by Activity Type</CardTitle>
                <CardDescription>Count comparison across workflow stages</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={statusByCategoryData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="Raised" fill="#3b82f6" />
                <Bar dataKey="Approved" fill="#22c55e" />
                <Bar dataKey="Rejected" fill="#ef4444" />
                <Bar dataKey="Pending" fill="#f59e0b" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Detailed Category Breakdown */}
      <Card className="shadow-lg">
        <CardHeader>
          <div className="flex items-center gap-3">
            <div className="p-3 bg-emerald-100 rounded-lg">
              <Activity className="h-5 w-5 text-emerald-600" />
            </div>
            <div>
              <CardTitle>Detailed Activity Type Breakdown</CardTitle>
              <CardDescription>In-depth analysis of claims by type and status</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div>
              <h3 className="text-lg mb-4 text-gray-900">Activity Type Value Comparison</h3>
              <ResponsiveContainer width="100%" height={350}>
                <BarChart data={valueComparisonData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis tickFormatter={(value) => formatCurrency(value)} />
                  <Tooltip 
                    formatter={(value: number) => formatCurrency(value)}
                    labelFormatter={(label) => label}
                  />
                  <Legend />
                  <Bar dataKey="Raised" fill="#3b82f6" />
                  <Bar dataKey="Approved" fill="#22c55e" />
                  <Bar dataKey="Credited" fill="#10b981" />
                </BarChart>
              </ResponsiveContainer>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
              {categoryData.slice(0, 3).map((cat, index) => (
                <Card key={index} className="shadow-md hover:shadow-lg transition-shadow">
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-base">{cat.activityType}</CardTitle>
                      <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200">
                        {cat.approvalRate.toFixed(1)}% approved
                      </Badge>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Raised:</span>
                        <span className="text-gray-900">{formatNumber(cat.raised)} ({formatCurrency(cat.raisedValue)})</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Approved:</span>
                        <span className="text-green-600">{formatNumber(cat.approved)} ({formatCurrency(cat.approvedValue)})</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Rejected:</span>
                        <span className="text-red-600">{formatNumber(cat.rejected)} ({formatCurrency(cat.rejectedValue)})</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Pending:</span>
                        <span className="text-orange-600">{formatNumber(cat.pending)} ({formatCurrency(cat.pendingValue)})</span>
                      </div>
                      <div className="h-px bg-gray-200 my-2" />
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Credited:</span>
                        <span className="text-emerald-600">{formatNumber(cat.credited)} ({formatCurrency(cat.creditedValue)})</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">Pending Credit:</span>
                        <span className="text-amber-600">{formatNumber(cat.pendingCredit)} ({formatCurrency(cat.pendingCreditValue)})</span>
                      </div>
                    </div>
                    <div className="pt-2">
                      <div className="flex justify-between text-xs text-gray-600 mb-1">
                        <span>Credit Rate</span>
                        <span>{cat.creditRate.toFixed(1)}%</span>
                      </div>
                      <Progress value={cat.creditRate} className="h-2" />
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Performance Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="border-t-4 border-t-green-500 shadow-lg hover:shadow-xl transition-shadow">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-green-100 rounded-lg">
                <Target className="h-6 w-6 text-green-600" />
              </div>
              <TrendingUp className="h-5 w-5 text-green-600" />
            </div>
            <h3 className="text-sm text-gray-600 mb-1">Best Performing</h3>
            <p className="text-xl text-gray-900 mb-1">{bestPerforming?.activityType || 'N/A'}</p>
            <p className="text-sm text-green-600">{bestPerforming?.approvalRate.toFixed(2) || 0}% approval rate</p>
          </CardContent>
        </Card>

        <Card className="border-t-4 border-t-blue-500 shadow-lg hover:shadow-xl transition-shadow">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-blue-100 rounded-lg">
                <DollarSign className="h-6 w-6 text-blue-600" />
              </div>
              <Activity className="h-5 w-5 text-blue-600" />
            </div>
            <h3 className="text-sm text-gray-600 mb-1">Top Activity Type</h3>
            <p className="text-xl text-gray-900 mb-1">{highestValue?.activityType || 'N/A'}</p>
            <p className="text-sm text-blue-600">{highestValue ? formatCurrency(highestValue.raisedValue, true) : '₹0'} raised</p>
          </CardContent>
        </Card>

        <Card className="border-t-4 border-t-emerald-500 shadow-lg hover:shadow-xl transition-shadow">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-emerald-100 rounded-lg">
                <Zap className="h-6 w-6 text-emerald-600" />
              </div>
              <CircleCheckBig className="h-5 w-5 text-emerald-600" />
            </div>
            <h3 className="text-sm text-gray-600 mb-1">Overall Credit Rate</h3>
            <p className="text-xl text-gray-900 mb-1">{calculateCreditRate()}%</p>
            <p className="text-sm text-emerald-600">{formatNumber(kpis.credited)} claims credited</p>
          </CardContent>
        </Card>

        <Card className="border-t-4 border-t-amber-500 shadow-lg hover:shadow-xl transition-shadow">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between mb-4">
              <div className="p-3 bg-amber-100 rounded-lg">
                <Package className="h-6 w-6 text-amber-600" />
              </div>
              <TriangleAlert className="h-5 w-5 text-amber-600" />
            </div>
            <h3 className="text-sm text-gray-600 mb-1">Pending Action</h3>
            <p className="text-xl text-gray-900 mb-1">{formatNumber(kpis.pendingCredit)}</p>
            <p className="text-sm text-amber-600">{formatCurrency(kpis.pendingCreditValue)} awaiting credit</p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

