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 RetailDailySummary: 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_RETAIL}?date=${dateStr}`);
      setReportData(res.data?.result || null);
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch retail 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_RETAIL_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 = `retail-daily-summary-${dateStr}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(objectUrl);

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

  const summary = reportData?.financialSummary;
  const open = summary?.opening || {};
  const close = summary?.closing || {};

  const retailItems = (reportData?.retailItemized || []).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: 'walkInName',
      key: 'walkInName',
    },
    {
      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' : 'purple'}>{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) => (
        <div>
          <strong>{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">{record.unit || record.saleUnit || ''}</span></strong>
          {record.unit !== 'KG' && record.quantityKg ? (
            <div className="text-[11px] text-gray-500 font-normal">({fmtQty(record.quantityKg)} KG)</div>
          ) : null}
        </div>
      ),
    },
    {
      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: '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: 'Allocated Qty',
      dataIndex: 'allocatedQty',
      key: 'allocatedQty',
      align: 'right' as const,
      render: (val: number, record: any) => (
        <div>
          <span>{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">{record.allocatedUnit || record.unit || ''}</span></span>
          {record.allocatedUnit !== 'KG' && record.allocatedKg ? (
            <div className="text-[11px] text-gray-400 font-normal">({fmtQty(record.allocatedKg)} KG)</div>
          ) : null}
        </div>
      ),
    },
    {
      title: 'Sold Qty',
      dataIndex: 'soldQty',
      key: 'soldQty',
      align: 'right' as const,
      render: (val: number) => (
        <div>
          <span className="text-blue-600 font-semibold">{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">KG</span></span>
        </div>
      ),
    },
    {
      title: 'Remaining Stock Qty',
      dataIndex: 'remainingQty',
      key: 'remainingQty',
      align: 'right' as const,
      render: (val: number) => (
        <div>
          <span className="text-emerald-600 font-bold">{fmtQty(val)} <span className="text-xs text-gray-500 ml-1">KG</span></span>
        </div>
      ),
    },
  ];

  return (
    <AppContainer
      title="Retail 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 (Retail)
            </Title>
          </Card>

          {/* Financial Summary 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 text-center font-bold">
                    <th className="p-2 border border-slate-700 w-1/2 uppercase">RETAIL METRICS</th>
                    <th className="p-2 border border-slate-700 w-1/2 uppercase">AMOUNT / VALUE</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Total Retail Sales Revenue</td>
                    <td className="p-2 border border-slate-300 text-right font-bold text-emerald-700">₹{fmt(open.sales)}</td>
                  </tr>
                  {/* <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Cost of Goods Sold (COGS)</td>
                    <td className="p-2 border border-slate-300 text-right">₹{fmt(open.cogs)}</td>
                  </tr> */}
                  <tr className="bg-emerald-100 font-bold text-emerald-950">
                    <td className="p-2 border border-slate-300">Gross Profit Amount</td>
                    <td className="p-2 border border-slate-300 text-right">₹{fmt(open.grossAmount)}</td>
                  </tr>
                  {/* <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Total Retail Expenses</td>
                    <td className="p-2 border border-slate-300 text-right text-red-600">₹{fmt(open.expenses)}</td>
                  </tr> */}
                  <tr className="bg-emerald-200 font-extrabold text-emerald-950 text-base">
                    <td className="p-3 border border-slate-300">NET RETAIL PROFIT</td>
                    <td className="p-3 border border-slate-300 text-right">₹{fmt(open.profit)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Total Allocated Stock Qty (Kg)</td>
                    <td className="p-2 border border-slate-300 text-right font-semibold">{fmtQty(open.allocatedQty)} kg</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Allocated Stock Valuation</td>
                    <td className="p-2 border border-slate-300 text-right">₹{fmt(open.allocatedValue)}</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2 border border-slate-300">Retail Spoilage Qty (Kg)</td>
                    <td className="p-2 border border-slate-300 text-right text-amber-600">{fmtQty(close.spoilageQty)} kg</td>
                  </tr>
                  <tr className="bg-blue-100 font-bold text-blue-950">
                    <td className="p-2 border border-slate-300">Remaining Retail Stock Valuation</td>
                    <td className="p-2 border border-slate-300 text-right">₹{fmt(close.remainingRetailStockValue)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </Card>

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

                pageData.forEach(({ quantity, totalAmt, profit, isFlexible, unit, isArrival }: any) => {
                  totalQty += Number(quantity || 0);
                  totalSales += Number(totalAmt || 0);
                  if (isArrival || (!isFlexible && unit !== 'PIECES')) {
                    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" className="text-emerald-700">
                      ₹{fmt(totalProfit)}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                );
              }}
            />
          </Card>

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

export default RetailDailySummary;
