'use client';

import { useMemo, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { type Customer, type SalesInvoice, type CustomerPayment, type SalesRep } from '@/lib/types';
import { formatCurrency } from '@/lib/currency-formatter';

type SalesRepReportProps = {
  salesReps: SalesRep[];
  customers: Customer[];
  invoices: SalesInvoice[];
  payments: CustomerPayment[];
  t: any;
  currencySymbol?: string;
};

const isWithinRange = (date: Date, from?: Date, to?: Date) => {
  if (from && date < from) return false;
  if (to && date > to) return false;
  return true;
};

export default function SalesRepReport({ salesReps, customers, invoices, payments, t, currencySymbol = '$' }: SalesRepReportProps) {
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');

  const customerById = useMemo(() => {
    const map = new Map<string, Customer>();
    customers.forEach((c) => map.set(c.id, c));
    return map;
  }, [customers]);

  const from = useMemo(() => (fromDate ? new Date(`${fromDate}T00:00:00`) : undefined), [fromDate]);
  const to = useMemo(() => (toDate ? new Date(`${toDate}T23:59:59`) : undefined), [toDate]);

  const rows = useMemo(() => {
    return salesReps.map((rep) => {
      const repCustomers = customers.filter((c) => c.salesRepId === rep.id);
      const receivables = repCustomers.reduce((sum, c) => sum + (c.balance || 0), 0);

      const totalSales = invoices.reduce((sum, inv) => {
        const repId = inv.salesRepId || customerById.get(inv.customerId)?.salesRepId || '';
        if (repId !== rep.id) return sum;
        const invDate = new Date(inv.date);
        if (!isWithinRange(invDate, from, to)) return sum;
        return sum + (inv.grandTotal || 0);
      }, 0);

      const totalCollections = payments.reduce((sum, pay) => {
        const repId = pay.salesRepId || '';
        if (repId !== rep.id) return sum;
        const payDate = new Date(pay.date);
        if (!isWithinRange(payDate, from, to)) return sum;
        return sum + (pay.amount || 0);
      }, 0);

      return {
        id: rep.id,
        name: rep.name,
        customersCount: repCustomers.length,
        receivables,
        totalSales,
        totalCollections,
      };
    });
  }, [salesReps, customers, invoices, payments, customerById, from, to]);

  const totals = useMemo(() => {
    return rows.reduce((acc, row) => {
      acc.customersCount += row.customersCount;
      acc.receivables += row.receivables;
      acc.totalSales += row.totalSales;
      acc.totalCollections += row.totalCollections;
      return acc;
    }, { customersCount: 0, receivables: 0, totalSales: 0, totalCollections: 0 });
  }, [rows]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t?.salesRepReportTitle ?? 'Sales Rep Report'}</CardTitle>
        <CardDescription>{t?.salesRepReportDescription ?? 'Receivables and collections per sales rep.'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div>
            <label className="text-sm font-medium">{t?.fromDateLabel ?? 'From date'}</label>
            <Input type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)} />
          </div>
          <div>
            <label className="text-sm font-medium">{t?.toDateLabel ?? 'To date'}</label>
            <Input type="date" value={toDate} onChange={(e) => setToDate(e.target.value)} />
          </div>
        </div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t?.salesRepNameLabel ?? 'Sales Rep'}</TableHead>
              <TableHead className="text-end">{t?.salesRepCustomersCountLabel ?? 'Customers'}</TableHead>
              <TableHead className="text-end">{t?.salesRepReceivablesLabel ?? 'Receivables'}</TableHead>
              <TableHead className="text-end">{t?.salesRepSalesLabel ?? 'Sales'}</TableHead>
              <TableHead className="text-end">{t?.salesRepCollectionsLabel ?? 'Collections'}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
                  {t?.salesRepNoData ?? 'No data found.'}
                </TableCell>
              </TableRow>
            ) : (
              rows.map((row) => (
                <TableRow key={row.id}>
                  <TableCell className="font-medium">{row.name}</TableCell>
                  <TableCell className="text-end font-mono">{row.customersCount}</TableCell>
                  <TableCell className="text-end font-mono text-red-600">{formatCurrency(row.receivables, currencySymbol)}</TableCell>
                  <TableCell className="text-end font-mono">{formatCurrency(row.totalSales, currencySymbol)}</TableCell>
                  <TableCell className="text-end font-mono text-green-600">{formatCurrency(row.totalCollections, currencySymbol)}</TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
          <TableFooter>
            <TableRow className="bg-muted/50 font-bold">
              <TableCell>{t?.total ?? 'Total'}</TableCell>
              <TableCell className="text-end font-mono">{totals.customersCount}</TableCell>
              <TableCell className="text-end font-mono text-red-600">{formatCurrency(totals.receivables, currencySymbol)}</TableCell>
              <TableCell className="text-end font-mono">{formatCurrency(totals.totalSales, currencySymbol)}</TableCell>
              <TableCell className="text-end font-mono text-green-600">{formatCurrency(totals.totalCollections, currencySymbol)}</TableCell>
            </TableRow>
          </TableFooter>
        </Table>
      </CardContent>
    </Card>
  );
}
