'use client';

import { useMemo, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { format, startOfMonth, endOfMonth, startOfYear, endOfYear, subMonths } from 'date-fns';
import { Download, BarChart3 } from 'lucide-react';
import { formatCurrency } from '@/lib/currency-formatter';

type AdvancedChecksAnalyticsProps = {
  checks: any[];
  t: any;
  currencySymbol?: string;
};

export function AdvancedChecksAnalytics({
  checks,
  t,
  currencySymbol = '$'
}: AdvancedChecksAnalyticsProps) {
  const [timeRange, setTimeRange] = useState('all');
  const [reservationFilter, setReservationFilter] = useState('all');

  const today = useMemo(() => new Date(), []);

  const getDateRange = () => {
    const now = new Date();
    switch (timeRange) {
      case 'current-month':
        return { from: startOfMonth(now), to: endOfMonth(now) };
      case 'last-month':
        const last = subMonths(now, 1);
        return { from: startOfMonth(last), to: endOfMonth(last) };
      case 'last-3-months':
        const three = subMonths(now, 3);
        return { from: startOfMonth(three), to: endOfMonth(now) };
      case 'current-year':
        return { from: startOfYear(now), to: endOfYear(now) };
      default:
        return { from: null, to: null };
    }
  };

  const filteredChecks = useMemo(() => {
    const dateRange = getDateRange();
    return (checks || []).filter((check) => {
      // Status filter
      if (reservationFilter !== 'all') {
        const reservationStatus = check.reservationStatus || 'available';
        if (reservationFilter !== reservationStatus) return false;
      }

      // Date filter
      if (dateRange.from && dateRange.to) {
        const checkDate = new Date(check.checkDate);
        if (checkDate < dateRange.from || checkDate > dateRange.to) return false;
      }

      return true;
    });
  }, [checks, timeRange, reservationFilter]);

  const statistics = useMemo(() => {
    const rows = filteredChecks;

    const byStatus = {
      available: { count: 0, amount: 0 },
      reserved: { count: 0, amount: 0 },
      endorsed: { count: 0, amount: 0 },
      pending: { count: 0, amount: 0 },
      cleared: { count: 0, amount: 0 },
      rejected: { count: 0, amount: 0 },
      returned: { count: 0, amount: 0 },
    };

    rows.forEach((check) => {
      const reservationStatus = check.reservationStatus || 'available';
      const status = check.status || 'pending';
      const amount = Number(check.amount || 0);

      if (byStatus[reservationStatus as keyof typeof byStatus]) {
        byStatus[reservationStatus as keyof typeof byStatus].count += 1;
        byStatus[reservationStatus as keyof typeof byStatus].amount += amount;
      }
    });

    const byMonthAndSupplier = new Map<string, Map<string, { count: number; amount: number }>>();
    rows.forEach((check) => {
      const month = format(new Date(check.checkDate), 'yyyy-MM');
      const supplier = String(check.endorsedToName || check.supplierName || 'unknown').trim();

      if (!byMonthAndSupplier.has(month)) {
        byMonthAndSupplier.set(month, new Map());
      }

      const supplierMap = byMonthAndSupplier.get(month)!;
      const current = supplierMap.get(supplier) || { count: 0, amount: 0 };
      current.count += 1;
      current.amount += Number(check.amount || 0);
      supplierMap.set(supplier, current);
    });

    const monthlyTrends = Array.from(byMonthAndSupplier.entries())
      .map(([month, suppliers]) => ({
        month,
        totalCount: Array.from(suppliers.values()).reduce((sum, s) => sum + s.count, 0),
        totalAmount: Array.from(suppliers.values()).reduce((sum, s) => sum + s.amount, 0),
        topSuppliers: Array.from(suppliers.entries())
          .map(([supplier, stats]) => ({ supplier, ...stats }))
          .sort((a, b) => b.amount - a.amount)
          .slice(0, 3),
      }))
      .sort((a, b) => a.month.localeCompare(b.month));

    const totalCount = rows.length;
    const totalAmount = rows.reduce((sum, r) => sum + Number(r.amount || 0), 0);

    return {
      byStatus,
      monthlyTrends,
      totalCount,
      totalAmount,
      averageCheck: totalCount > 0 ? totalAmount / totalCount : 0,
      endorsedCount: byStatus.endorsed.count,
      endorsedAmount: byStatus.endorsed.amount,
      reservedCount: byStatus.reserved.count,
      reservedAmount: byStatus.reserved.amount,
      availableCount: byStatus.available.count,
      availableAmount: byStatus.available.amount,
    };
  }, [filteredChecks]);

  const handleExportAnalytics = () => {
    const monthlyData = statistics.monthlyTrends.map((trend) => [
      trend.month,
      trend.totalCount,
      trend.totalAmount,
    ]);

    let csv = 'الشهر,العدد,المبلغ الإجمالي\n';
    monthlyData.forEach((row) => {
      csv += row.map((cell) => `"${cell}"`).join(',') + '\n';
    });

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `checks-analytics-${format(new Date(), 'yyyy-MM-dd')}.csv`;
    link.click();
  };

  return (
    <div className="space-y-6">
      {/* الفلاتر */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t.filters ?? 'الفلاتر'}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <Label htmlFor="time-range" className="text-sm font-medium">{t.timeRange ?? 'الفترة الزمنية'}</Label>
              <Select value={timeRange} onValueChange={setTimeRange}>
                <SelectTrigger id="time-range" className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t.allTime ?? 'كل الفترة'}</SelectItem>
                  <SelectItem value="current-month">{t.currentMonth ?? 'الشهر الحالي'}</SelectItem>
                  <SelectItem value="last-month">{t.lastMonth ?? 'الشهر الماضي'}</SelectItem>
                  <SelectItem value="last-3-months">{t.last3Months ?? 'آخر 3 أشهر'}</SelectItem>
                  <SelectItem value="current-year">{t.currentYear ?? 'السنة الحالية'}</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="reservation-filter" className="text-sm font-medium">{t.status ?? 'الحالة'}</Label>
              <Select value={reservationFilter} onValueChange={setReservationFilter}>
                <SelectTrigger id="reservation-filter" className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t.allStatuses ?? 'جميع الحالات'}</SelectItem>
                  <SelectItem value="available">{t.available ?? 'متاح'}</SelectItem>
                  <SelectItem value="reserved">{t.reserved ?? 'محجوز'}</SelectItem>
                  <SelectItem value="endorsed">{t.endorsed ?? 'مجيّر'}</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <Button onClick={handleExportAnalytics} className="gap-2 mt-4">
            <Download className="w-4 h-4" />
            {t.export ?? 'تصدير'}
          </Button>
        </CardContent>
      </Card>

      {/* إحصائيات الحالات */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.endorsed ?? 'الشيكات المجيّرة'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="text-2xl font-bold">{statistics.endorsedCount}</div>
              <p className="text-sm text-muted-foreground">{formatCurrency(statistics.endorsedAmount, currencySymbol)}</p>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.reserved ?? 'الشيكات المحجوزة'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="text-2xl font-bold">{statistics.reservedCount}</div>
              <p className="text-sm text-muted-foreground">{formatCurrency(statistics.reservedAmount, currencySymbol)}</p>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.available ?? 'الشيكات المتاحة'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="text-2xl font-bold">{statistics.availableCount}</div>
              <p className="text-sm text-muted-foreground">{formatCurrency(statistics.availableAmount, currencySymbol)}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* الاتجاهات الشهرية */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            {t.monthlyTrends ?? 'الاتجاهات الشهرية'}
          </CardTitle>
          <CardDescription>{t.checksMovementByMonth ?? 'حركة الشيكات حسب الشهر'}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="text-right">{t.month ?? 'الشهر'}</TableHead>
                  <TableHead className="text-right">{t.checksCount ?? 'عدد الشيكات'}</TableHead>
                  <TableHead className="text-right">{t.totalAmount ?? 'المبلغ الإجمالي'}</TableHead>
                  <TableHead className="text-right">{t.topSuppliers ?? 'أكثر الموردين'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {statistics.monthlyTrends.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-6 text-muted-foreground">
                      {t.noData ?? 'لا توجد بيانات'}
                    </TableCell>
                  </TableRow>
                ) : (
                  statistics.monthlyTrends.map((trend) => (
                    <TableRow key={trend.month}>
                      <TableCell className="font-medium">{trend.month}</TableCell>
                      <TableCell>{trend.totalCount}</TableCell>
                      <TableCell>{formatCurrency(trend.totalAmount, currencySymbol)}</TableCell>
                      <TableCell className="text-sm">
                        {trend.topSuppliers.map((supplier) => (
                          <div key={supplier.supplier} className="flex items-center justify-between gap-2 mb-1">
                            <span>{supplier.supplier}</span>
                            <Badge variant="outline">{supplier.count}</Badge>
                          </div>
                        ))}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* توزيع الشيكات */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t.statusDistribution ?? 'توزيع الشيكات حسب الحالة'}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2">
            {Object.entries(statistics.byStatus).map(([status, data]) => (
              (data as any).count > 0 && (
                <div key={status} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="font-medium capitalize">
                      {status === 'endorsed' && 'مجيّر'}
                      {status === 'reserved' && 'محجوز'}
                      {status === 'available' && 'متاح'}
                      {status === 'pending' && 'قيد الانتظار'}
                      {status === 'cleared' && 'مقبول'}
                      {status === 'rejected' && 'مرفوض'}
                      {status === 'returned' && 'مرجع'}
                    </h3>
                    <Badge>{(data as any).count}</Badge>
                  </div>
                  <p className="text-lg font-semibold">{formatCurrency((data as any).amount, currencySymbol)}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {((((data as any).amount / statistics.totalAmount) || 0) * 100).toFixed(1)}% {t.ofTotal ?? 'من الإجمالي'}
                  </p>
                </div>
              )
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
