import React, { useEffect, useState } from 'react';
import {
  DatePicker,
  Button,
  Card,
  Spin,
  Table,
  message,
  Tag,
  Typography,
} from 'antd';
import { FilePdfOutlined, RedoOutlined } from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

const { Title, Text } = Typography;

const fmt = (val?: number | null) => {
  const n = Number(val ?? 0);
  return isNaN(n) ? '0.00' : n.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const fmtQty = (val?: number | null) => {
  const n = Number(val ?? 0);
  return isNaN(n) ? '0.000' : n.toLocaleString('en-IN', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
};

export const WholesaleDailySummary: React.FC = () => {
  const [selectedDate, setSelectedDate] = useState<Dayjs>(dayjs());
  const [loading, setLoading] = useState<boolean>(false);
  const [pdfLoading, setPdfLoading] = useState<boolean>(false);
  const [reportData, setReportData] = useState<any>(null);

  const fetchSummary = async (dateObj: Dayjs = selectedDate) => {
    setLoading(true);
    try {
      const dateStr = dateObj.format('YYYY-MM-DD');
      const res = await jwtAxios.get(`${ENDPOINTS.DAILY_SUMMARY_WHOLESALE}?date=${dateStr}`);
      setReportData(res.data?.result || null);
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch wholesale daily summary');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSummary(selectedDate);
  }, [selectedDate]);

  const handleReset = () => {
    const today = dayjs();
    setSelectedDate(today);
    fetchSummary(today);
  };


  const handleExportPdf = async () => {
    setPdfLoading(true);
    try {
      const dateStr = selectedDate.format('YYYY-MM-DD');
      const response = await jwtAxios.get(`${ENDPOINTS.DAILY_SUMMARY_WHOLESALE_PDF}?date=${dateStr}`, {
        responseType: 'blob',
      });

      const blob = new Blob([response.data], { type: 'application/pdf' });
      const objectUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = objectUrl;
      link.download = `wholesale-daily-summary-${dateStr}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(objectUrl);

      message.success('Wholesale Daily Summary PDF downloaded successfully');
    } catch (err: any) {
      message.error('Failed to export PDF');
    } finally {
      setPdfLoading(false);
    }
  };

  const summary = reportData?.financialSummary || {};
  const sales = summary?.sales ?? summary?.opening?.sales ?? 0;
  // const cogs = summary?.cogs ?? summary?.opening?.cogs ?? 0;
  const grossAmount = summary?.grossAmount ?? summary?.opening?.grossAmount ?? 0;
  const expenses = summary?.expenses ?? summary?.opening?.expenses ?? 0;
  const profit = summary?.profit ?? summary?.opening?.profit ?? 0;
  const salesCollection = summary?.salesCollection ?? summary?.closing?.salesCollection ?? 0;
  const supplierCollection = summary?.supplierCollection ?? summary?.closing?.supplierCollection ?? 0;
  const purchasesTotal = summary?.purchasesTotal ?? summary?.closing?.purchase ?? 0;
  const customerOutstanding = summary?.customerOutstanding ?? summary?.opening?.outstanding ?? 0;
  const supplierOutstanding = summary?.supplierOutstanding ?? summary?.closing?.outstanding ?? 0;

  const wholesaleItems = (reportData?.wholesaleItemized || []).map((item: any, idx: number) => ({
    key: idx,
    ...item,
  }));

  const stockMovements = (reportData?.stockMovements || []).map((m: any, idx: number) => ({
    key: idx,
    ...m,
  }));

  const itemizedColumns = [
    {
      title: '#',
      dataIndex: 'key',
      key: 'key',
      width: 50,
      render: (v: number) => v + 1,
    },
    {
      title: 'Invoice No',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      render: (val: string) => <Tag color="blue">{val}</Tag>,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: 'Vegetable',
      dataIndex: 'vegetableName',
      key: 'vegetableName',
    },
    {
      title: 'Lot No',
      dataIndex: 'lotNo',
      key: 'lotNo',
      render: (val: string, record: any) => (
        <span className="inline-flex items-center gap-1">
          <Tag color={record.isArrival ? 'gold' : 'orange'}>{val}</Tag>
          {record.isArrival && (
            <Tag color={record.isSettled ? 'green' : 'default'} className="text-[10px] px-1 py-0 m-0">
              {record.isSettled ? 'Settled' : 'Unsettled'}
            </Tag>
          )}
        </span>
      ),
    },
    {
      title: 'Qty Sold',
      dataIndex: 'quantity',
      key: 'quantity',
      align: 'right' as const,
      render: (val: number, record: any) => <strong>{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">{record.unit || record.saleUnit || ''}</span></strong>,
    },
    {
      title: 'Cost Price (₹)',
      dataIndex: 'costPerUnit',
      key: 'costPerUnit',
      align: 'right' as const,
      render: (val: number, record: any) =>
        record.isArrival || record.isFlexible || record.unit === 'PIECES' || val == null ? '-' : fmt(val),
    },
    {
      title: 'Selling Rate (₹)',
      dataIndex: 'sellingRate',
      key: 'sellingRate',
      align: 'right' as const,
      render: (val: number) => fmt(val),
    },
    {
      title: 'Sales Amount (₹)',
      dataIndex: 'totalAmt',
      key: 'totalAmt',
      align: 'right' as const,
      render: (val: number) => <strong className="text-emerald-700">₹{fmt(val)}</strong>,
    },
    {
      title: 'Cost Total (₹)',
      dataIndex: 'costTotal',
      key: 'costTotal',
      align: 'right' as const,
      render: (val: number, record: any) => (!record.isArrival && (record.isFlexible || record.unit === 'PIECES') ? '-' : `₹${fmt(val)}`),
    },
    {
      title: 'Profit (₹)',
      dataIndex: 'profit',
      key: 'profit',
      align: 'right' as const,
      render: (val: number, record: any) => {
        if (!record.isArrival && (record.isFlexible || record.unit === 'PIECES')) {
          return (
            <div>
              <span className="text-gray-400 font-semibold">-</span>
              <div className="text-[10px] text-amber-600 font-normal">(Flexible)</div>
            </div>
          );
        }
        return (
          <div>
            <span className={val >= 0 ? 'text-green-600 font-bold' : 'text-red-600 font-bold'}>
              ₹{fmt(val)}
            </span>
            {record.isArrival && (
              <div className="text-[10px] text-gray-500 font-normal">
                {record.isSettled ? '(4% Comm)' : '(Pending Settlement)'}
              </div>
            )}
          </div>
        );
      },
    },
  ];

  const stockColumns = [
    {
      title: 'Lot No',
      dataIndex: 'lotNo',
      key: 'lotNo',
      render: (val: string) => <Tag color="purple">{val}</Tag>,
    },
    {
      title: 'Vegetable',
      dataIndex: 'vegetableName',
      key: 'vegetableName',
    },
    {
      title: 'Supplier',
      dataIndex: 'supplierName',
      key: 'supplierName',
      render: (val: string, record: any) => val || record.cashSupplierName || '-',
    },
    {
      title: 'Purchased Qty',
      dataIndex: 'purchasedQty',
      key: 'purchasedQty',
      align: 'right' as const,
      render: (val: number, record: any) => <span>{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">{record.unit || ''}</span></span>,
    },
    {
      title: 'Wholesale Sold Qty',
      dataIndex: 'wholesaleSoldQty',
      key: 'wholesaleSoldQty',
      align: 'right' as const,
      render: (val: number, record: any) => (
        <div>
          <span className="text-blue-600 font-semibold">
            {fmtQty(val ?? record.soldQty)} <span className="text-xs text-gray-500 ml-1">{record.unit || ''}</span>
          </span>
          {record.secondarySoldText && (
            <div className="text-[11px] text-purple-700 font-medium">
              (+ {record.secondarySoldText})
            </div>
          )}
        </div>
      ),
    },
    {
      title: 'Moved to Retail',
      dataIndex: 'retailMovedQty',
      key: 'retailMovedQty',
      align: 'right' as const,
      render: (val: number, record: any) => (
        <span className="text-amber-600 font-semibold">{fmtQty(val || 0)} <span className="text-xs text-gray-500 ml-1">{record.unit || ''}</span></span>
      ),
    },
    {
      title: 'Remaining Stock Qty',
      dataIndex: 'remainingQty',
      key: 'remainingQty',
      align: 'right' as const,
      render: (val: number, record: any) => <span className="text-emerald-600 font-bold">{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">{record.unit || ''}</span></span>,
    },
  ];

  return (

    <AppContainer
      title="Wholesale Daily Summary & Financial Report"
      headerAction={
        <div className="flex items-center gap-3">
          <DatePicker
            value={selectedDate}
            onChange={(d) => d && setSelectedDate(d)}
            format="DD-MM-YYYY"
            allowClear={false}
            className="w-44"
            placeholder="Select Date"
          />
          <Button icon={<RedoOutlined />} onClick={handleReset} loading={loading}>
            Reset
          </Button>
          <Button
            type="primary"
            icon={<FilePdfOutlined />}
            onClick={handleExportPdf}
            loading={pdfLoading}
            className="bg-emerald-600 hover:bg-emerald-700"
          >
            PDF Download
          </Button>
        </div>
      }
    >
      <Spin spinning={loading}>
        <div className="space-y-6">
          {/* Header Card */}
          <Card className="shadow-sm! border-gray-200! text-center! bg-slate-900! text-white! rounded-lg! py-1!">
            <Text className="text-gray-300! text-sm!">Date : {selectedDate.format('DD-MM-YYYY')}</Text>
            <Title level={3} className="text-white! mb-0! font-bold uppercase tracking-wide">
              Financial Summary (Wholesale)
            </Title>
          </Card>

          {/* Financial Summary Boxed Card Table */}
          <Card className="shadow-sm! border-gray-300! p-0! overflow-hidden! rounded-lg!">
            <div className="overflow-x-auto">
              <table className="w-full text-sm border-collapse border border-slate-300">
                <thead>
                  <tr className="bg-slate-800 text-white font-bold text-center">
                    <th className="p-2.5 border border-slate-700 w-1/2 uppercase text-left pl-4">WHOLESALE METRICS</th>
                    <th className="p-2.5 border border-slate-700 w-1/2 uppercase text-right pr-4">AMOUNT / VALUE</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 font-semibold text-slate-700 pl-4">Total Wholesale Sales Revenue</td>
                    <td className="p-2.5 border border-slate-300 text-right font-bold text-emerald-700 pr-4">₹{fmt(sales)}</td>
                  </tr>
                  {/* <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 text-slate-700 pl-4">Cost of Goods Sold (COGS)</td>
                    <td className="p-2.5 border border-slate-300 text-right font-medium pr-4">₹{fmt(cogs)}</td>
                  </tr> */}
                  <tr className="bg-emerald-50 font-bold text-emerald-950">
                    <td className="p-2.5 border border-slate-300 pl-4">Gross Profit Amount</td>
                    <td className="p-2.5 border border-slate-300 text-right pr-4">₹{fmt(grossAmount)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 text-slate-700 pl-4">Total Expenses</td>
                    <td className="p-2.5 border border-slate-300 text-right text-red-600 font-medium pr-4">₹{fmt(expenses)}</td>
                  </tr>
                  <tr className="bg-emerald-200 font-extrabold text-emerald-950 text-base">
                    <td className="p-3 border border-slate-300 pl-4">NET WHOLESALE PROFIT</td>
                    <td className="p-3 border border-slate-300 text-right pr-4">₹{fmt(profit)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 text-slate-700 pl-4">Today's Customer Receipts (Collection)</td>
                    <td className="p-2.5 border border-slate-300 text-right font-semibold text-blue-700 pr-4">₹{fmt(salesCollection)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 text-slate-700 pl-4">Today's Supplier Payments</td>
                    <td className="p-2.5 border border-slate-300 text-right font-medium pr-4">₹{fmt(supplierCollection)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2.5 border border-slate-300 text-slate-700 pl-4">Today's Total Purchases</td>
                    <td className="p-2.5 border border-slate-300 text-right font-medium pr-4">₹{fmt(purchasesTotal)}</td>
                  </tr>
                  <tr className="bg-slate-50 font-semibold">
                    <td className="p-2.5 border border-slate-300 text-slate-800 pl-4">Total Customer Outstanding Balance</td>
                    <td className="p-2.5 border border-slate-300 text-right text-amber-700 pr-4">₹{fmt(customerOutstanding)}</td>
                  </tr>
                  <tr className="bg-slate-50 font-semibold">
                    <td className="p-2.5 border border-slate-300 text-slate-800 pl-4">Total Supplier Outstanding Balance</td>
                    <td className="p-2.5 border border-slate-300 text-right text-purple-700 pr-4">₹{fmt(supplierOutstanding)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>


          {/* Wholesale Itemised Profit Table */}
          <Card title="Wholesale Sales Itemised Profit Breakdown" className="shadow-sm border-gray-200 rounded-lg">
            <Table<any>
              dataSource={wholesaleItems}
              columns={itemizedColumns}
              pagination={false}
              size="small"
              bordered
              summary={(pageData: readonly any[]) => {
                let totalQty = 0;
                let totalSales = 0;
                let totalCost = 0;
                let totalProfit = 0;

                pageData.forEach(({ quantity, totalAmt, costTotal, profit, isFlexible, unit, isArrival }: any) => {
                  totalQty += Number(quantity || 0);
                  totalSales += Number(totalAmt || 0);
                  if (isArrival || (!isFlexible && unit !== 'PIECES')) {
                    totalCost += Number(costTotal || 0);
                    totalProfit += Number(profit || 0);
                  }
                });

                return (
                  <Table.Summary.Row className="bg-emerald-50 font-bold">
                    <Table.Summary.Cell index={0} colSpan={5} align="right">
                      TOTAL:
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align="right">
                      {fmtQty(totalQty)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={2} colSpan={2} />
                    <Table.Summary.Cell index={3} align="right">
                      ₹{fmt(totalSales)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={4} align="right">
                      ₹{fmt(totalCost)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={5} align="right" className="text-emerald-700">
                      ₹{fmt(totalProfit)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                );
              }}
            />
          </Card>

          {/* Stock Movements Card */}
          <Card title="Daily Stock Movements (Purchased vs Sold)" className="shadow-sm border-gray-200 rounded-lg">
            <Table
              dataSource={stockMovements}
              columns={stockColumns}
              pagination={false}
              size="small"
              bordered
            />
          </Card>
        </div>
      </Spin>
    </AppContainer>
  );
};

export default WholesaleDailySummary;
