'use client';

import { useMemo, useState } from 'react';
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { format } from 'date-fns';
import { Download, Filter } from 'lucide-react';
import { formatCurrency } from '@/lib/currency-formatter';

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

export function EndorsedChecksReport({
  checks,
  t,
  currencySymbol = '$'
}: EndorsedChecksReportProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [supplierFilter, setSupplierFilter] = useState('all');
  const [bankFilter, setBankFilter] = useState('all');
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const [minAmount, setMinAmount] = useState('');
  const [maxAmount, setMaxAmount] = useState('');

  const supplierOptions = useMemo(() => {
    return Array.from(new Set(
      (checks || [])
        .map((c) => String(c.endorsedToName || c.supplierName || '').trim())
        .filter(Boolean)
    )).sort((a, b) => a.localeCompare(b, 'ar'));
  }, [checks]);

  const bankOptions = useMemo(() => {
    return Array.from(new Set(
      (checks || [])
        .map((c) => String(c.bankName || '').trim())
        .filter(Boolean)
    )).sort((a, b) => a.localeCompare(b, 'ar'));
  }, [checks]);

  const filteredChecks = useMemo(() => {
    const min = minAmount.trim() === '' ? null : Number(minAmount);
    const max = maxAmount.trim() === '' ? null : Number(maxAmount);
    const q = searchQuery.trim().toLowerCase();

    return (checks || []).filter((check) => {
      const checkDate = format(new Date(check.checkDate), 'yyyy-MM-dd');
      const amount = Number(check.amount || 0);
      const text = [
        String(check.checkNumber || ''),
        String(check.bankName || ''),
        String(check.endorsedToName || check.supplierName || ''),
        String(check.currency || ''),
      ].join(' ').toLowerCase();

      if (q && !text.includes(q)) return false;
      if (supplierFilter !== 'all' && String(check.endorsedToName || check.supplierName || '').trim() !== supplierFilter) return false;
      if (bankFilter !== 'all' && String(check.bankName || '').trim() !== bankFilter) return false;
      if (fromDate && checkDate < fromDate) return false;
      if (toDate && checkDate > toDate) return false;
      if (min !== null && Number.isFinite(min) && amount < min) return false;
      if (max !== null && Number.isFinite(max) && amount > max) return false;

      return true;
    });
  }, [checks, minAmount, maxAmount, searchQuery, supplierFilter, bankFilter, fromDate, toDate]);

  const statistics = useMemo(() => {
    const rows = filteredChecks;
    const totalAmount = rows.reduce((sum, row) => sum + Number(row.amount || 0), 0);

    const bySupplier = new Map<string, { count: number; amount: number; currency: string }>();
    rows.forEach((row) => {
      const supplier = String(row.endorsedToName || row.supplierName || '-').trim() || '-';
      const current = bySupplier.get(supplier) || { count: 0, amount: 0, currency: row.currency };
      current.count += 1;
      current.amount += Number(row.amount || 0);
      bySupplier.set(supplier, current);
    });

    const topSuppliers = Array.from(bySupplier.entries())
      .map(([supplier, stats]) => ({ supplier, ...stats }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 5);

    const byBank = new Map<string, { count: number; amount: number }>();
    rows.forEach((row) => {
      const bank = String(row.bankName || '-').trim() || '-';
      const current = byBank.get(bank) || { count: 0, amount: 0 };
      current.count += 1;
      current.amount += Number(row.amount || 0);
      byBank.set(bank, current);
    });

    const topBanks = Array.from(byBank.entries())
      .map(([bank, stats]) => ({ bank, ...stats }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 5);

    return {
      totalCount: rows.length,
      totalAmount,
      topSuppliers,
      topBanks,
      averageCheck: rows.length > 0 ? totalAmount / rows.length : 0,
    };
  }, [filteredChecks]);

  const clearFilters = () => {
    setSearchQuery('');
    setSupplierFilter('all');
    setBankFilter('all');
    setFromDate('');
    setToDate('');
    setMinAmount('');
    setMaxAmount('');
  };

  const handleExport = () => {
    const rows = filteredChecks.map((check) => [
      check.checkNumber,
      format(new Date(check.checkDate), 'yyyy-MM-dd'),
      check.bankName,
      check.endorsedToName || check.supplierName,
      check.amount,
      check.currency,
      check.endorsedAt ? format(new Date(check.endorsedAt), 'yyyy-MM-dd') : 'N/A',
      check.endorsementReference || 'N/A',
    ]);

    const headers = ['رقم الشيك', 'تاريخ الشيك', 'البنك', 'المستفيد/المورد', 'المبلغ', 'العملة', 'تاريخ التجيير', 'المرجع'];

    let csv = headers.join(',') + '\n';
    rows.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 = `endorsed-checks-${format(new Date(), 'yyyy-MM-dd')}.csv`;
    link.click();
  };

  return (
    <div className="space-y-6">
      {/* إحصائيات رئيسية */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.totalEndorsed ?? 'إجمالي الشيكات المجيّرة'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statistics.totalCount}</div>
            <p className="text-xs text-muted-foreground mt-1">{t.checksCount ?? 'عدد الشيكات'}</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.totalAmount ?? 'إجمالي المبلغ'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(statistics.totalAmount, currencySymbol)}</div>
            <p className="text-xs text-muted-foreground mt-1">{t.totalEndorsedAmount ?? 'المبلغ المجيّر'}</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.averageCheck ?? 'متوسط الشيك'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(statistics.averageCheck, currencySymbol)}</div>
            <p className="text-xs text-muted-foreground mt-1">{t.averageAmount ?? 'المتوسط'}</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">{t.topSupplier ?? 'أكثر مورد'}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statistics.topSuppliers.length > 0 ? statistics.topSuppliers[0].count : 0}</div>
            <p className="text-xs text-muted-foreground mt-1">
              {statistics.topSuppliers.length > 0 ? statistics.topSuppliers[0].supplier : '-'}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* الفلاتر */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Filter className="w-4 h-4" />
            {t.filters ?? 'الفلاتر'}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            <div>
              <Label htmlFor="search" className="text-sm font-medium">{t.search ?? 'بحث'}</Label>
              <Input
                id="search"
                placeholder={t.searchPlaceholder ?? 'بحث برقم الشيك أو البنك...'}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="mt-1"
              />
            </div>

            <div>
              <Label htmlFor="supplier-filter" className="text-sm font-medium">{t.supplier ?? 'المورد'}</Label>
              <Select value={supplierFilter} onValueChange={setSupplierFilter}>
                <SelectTrigger id="supplier-filter" className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t.allSuppliers ?? 'جميع الموردين'}</SelectItem>
                  {supplierOptions.map((supplier) => (
                    <SelectItem key={supplier} value={supplier}>
                      {supplier}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="bank-filter" className="text-sm font-medium">{t.bank ?? 'البنك'}</Label>
              <Select value={bankFilter} onValueChange={setBankFilter}>
                <SelectTrigger id="bank-filter" className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t.allBanks ?? 'جميع البنوك'}</SelectItem>
                  {bankOptions.map((bank) => (
                    <SelectItem key={bank} value={bank}>
                      {bank}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="amount-range" className="text-sm font-medium">{t.amountRange ?? 'نطاق المبلغ'}</Label>
              <div className="flex gap-2 mt-1">
                <Input
                  placeholder={t.min ?? 'الحد الأدنى'}
                  type="number"
                  value={minAmount}
                  onChange={(e) => setMinAmount(e.target.value)}
                  className="flex-1"
                />
                <Input
                  placeholder={t.max ?? 'الحد الأقصى'}
                  type="number"
                  value={maxAmount}
                  onChange={(e) => setMaxAmount(e.target.value)}
                  className="flex-1"
                />
              </div>
            </div>

            <div>
              <Label htmlFor="from-date" className="text-sm font-medium">{t.fromDate ?? 'من التاريخ'}</Label>
              <Input
                id="from-date"
                type="date"
                value={fromDate}
                onChange={(e) => setFromDate(e.target.value)}
                className="mt-1"
              />
            </div>

            <div>
              <Label htmlFor="to-date" className="text-sm font-medium">{t.toDate ?? 'إلى التاريخ'}</Label>
              <Input
                id="to-date"
                type="date"
                value={toDate}
                onChange={(e) => setToDate(e.target.value)}
                className="mt-1"
              />
            </div>
          </div>

          <div className="flex gap-2">
            <Button onClick={clearFilters} variant="outline" className="gap-2">
              {t.clearFilters ?? 'مسح الفلاتر'}
            </Button>
            <Button onClick={handleExport} className="gap-2 ml-auto">
              <Download className="w-4 h-4" />
              {t.export ?? 'تصدير'}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* أعلى الموردين والبنوك */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">{t.topSuppliers ?? 'أكثر الموردين'}</CardTitle>
            <CardDescription>{t.byEndorsementAmount ?? 'حسب المبلغ المجيّر'}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {statistics.topSuppliers.length === 0 ? (
                <p className="text-sm text-muted-foreground">{t.noData ?? 'لا توجد بيانات'}</p>
              ) : (
                statistics.topSuppliers.map((item, idx) => (
                  <div key={idx} className="flex items-center justify-between border-b pb-3 last:border-0">
                    <div>
                      <p className="font-medium">{item.supplier}</p>
                      <p className="text-sm text-muted-foreground">{item.count} {t.checksCount ?? 'شيك'}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-semibold">{formatCurrency(item.amount, currencySymbol)}</p>
                      <p className="text-xs text-muted-foreground">{item.currency}</p>
                    </div>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">{t.topBanks ?? 'أكثر البنوك'}</CardTitle>
            <CardDescription>{t.byEndorsementAmount ?? 'حسب المبلغ المجيّر'}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {statistics.topBanks.length === 0 ? (
                <p className="text-sm text-muted-foreground">{t.noData ?? 'لا توجد بيانات'}</p>
              ) : (
                statistics.topBanks.map((item, idx) => (
                  <div key={idx} className="flex items-center justify-between border-b pb-3 last:border-0">
                    <div>
                      <p className="font-medium">{item.bank}</p>
                      <p className="text-sm text-muted-foreground">{item.count} {t.checksCount ?? 'شيك'}</p>
                    </div>
                    <p className="font-semibold">{formatCurrency(item.amount, currencySymbol)}</p>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* جدول الشيكات المجيّرة */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t.endorsedChecksList ?? 'قائمة الشيكات المجيّرة'}</CardTitle>
          <CardDescription>{filteredChecks.length} {t.checksFound ?? 'شيك'}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="text-right">{t.checkNumber ?? 'رقم الشيك'}</TableHead>
                  <TableHead className="text-right">{t.checkDate ?? 'تاريخ الشيك'}</TableHead>
                  <TableHead className="text-right">{t.bank ?? 'البنك'}</TableHead>
                  <TableHead className="text-right">{t.supplier ?? 'المورد/المستفيد'}</TableHead>
                  <TableHead className="text-right">{t.amount ?? 'المبلغ'}</TableHead>
                  <TableHead className="text-right">{t.endorse ?? 'الحالة'}</TableHead>
                  <TableHead className="text-right">{t.endorsementDate ?? 'تاريخ التجيير'}</TableHead>
                  <TableHead className="text-right">{t.reference ?? 'المرجع'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredChecks.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-6 text-muted-foreground">
                      {t.noChecksFound ?? 'لم يتم العثور على شيكات'}
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredChecks.map((check) => (
                    <TableRow key={check.id}>
                      <TableCell className="font-medium">{check.checkNumber}</TableCell>
                      <TableCell>{format(new Date(check.checkDate), 'yyyy-MM-dd')}</TableCell>
                      <TableCell>{check.bankName}</TableCell>
                      <TableCell>{check.endorsedToName || check.supplierName}</TableCell>
                      <TableCell>{formatCurrency(Number(check.amount || 0), currencySymbol)}</TableCell>
                      <TableCell>
                        <Badge variant="default" className="bg-green-600">
                          {t.endorsed ?? 'مجيّر'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {check.endorsedAt ? format(new Date(check.endorsedAt), 'yyyy-MM-dd') : '-'}
                      </TableCell>
                      <TableCell>{check.endorsementReference || '-'}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
