import React, { useEffect, useState, useCallback } from 'react';
import {
  DatePicker,
  Button,
  Card,
  Spin,
  message,
  Typography,
  Table,
  Row,
  Col,
  Divider
} from 'antd';
import {
  FilePdfOutlined,
  LeftOutlined,
  RightOutlined,
} 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 });
};

// Simple label-value row
const Row2: React.FC<{ label: string; value: string; bold?: boolean }> = ({ label, value, bold }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: '1px solid #f0f0f0' }}>
    <Text style={{ fontSize: 14, color: '#555' }}>{label}</Text>
    <Text strong={bold} style={{ fontSize: 14, color: '#111' }}>{value}</Text>
  </div>
);

// Section total row
const TotalRow: React.FC<{ label: string; value: string }> = ({ label, value }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', background: '#fafafa', border: '1px solid #d9d9d9', borderRadius: 6, marginTop: 8 }}>
    <Text strong style={{ fontSize: 15 }}>{label}</Text>
    <Text strong style={{ fontSize: 15 }}>{value}</Text>
  </div>
);

export const FinalDailyReport: 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 fetchReport = useCallback(async (dateObj: Dayjs = selectedDate) => {
    setLoading(true);
    try {
      const dateStr = dateObj.format('YYYY-MM-DD');
      const res = await jwtAxios.get(`${ENDPOINTS.FINAL_REPORT}?date=${dateStr}`);
      setReportData(res.data?.data || null);
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch final report');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  }, [selectedDate]);

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

  const handlePrevDay = () => setSelectedDate((prev) => prev.subtract(1, 'day'));
  const handleNextDay = () => {
    if (selectedDate.isSame(dayjs(), 'day') || selectedDate.isAfter(dayjs(), 'day')) return;
    setSelectedDate((prev) => prev.add(1, 'day'));
  };

  const handleExportPdf = async () => {
    setPdfLoading(true);
    try {
      const dateStr = selectedDate.format('YYYY-MM-DD');
      const response = await jwtAxios.get(`${ENDPOINTS.FINAL_REPORT_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 = `final-report-${dateStr}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(objectUrl);
      message.success('Final Report PDF downloaded successfully');
    } catch (err: any) {
      message.error('Failed to export PDF');
    } finally {
      setPdfLoading(false);
    }
  };

  const quickBill      = reportData?.quickBill      || { cash: 0, bank: 0, total: 0 };
  const creditBill     = reportData?.creditBill     || { cash: 0, bank: 0, totalAmount: 0, details: [] };
  const supplierPayment= reportData?.supplierPayment|| { cash: 0, bank: 0 };
  const customerPayment= reportData?.customerPayment|| { cash: 0, bank: 0 };
  const expenses       = reportData?.expenses       || { total: 0, details: [] };
  const purchases      = reportData?.purchases      || { total: 0, details: [] };
  const finalBalances  = reportData?.finalBalances  || { cash: 0, bank: 0 };
  const outstanding    = reportData?.outstanding    || { supplier: 0, customer: 0 };

  const totalIncome    = quickBill.total + creditBill.totalAmount + (customerPayment.cash + customerPayment.bank);
  const totalOutgoings = (supplierPayment.cash + supplierPayment.bank) + expenses.total;

  const cardStyle = { marginBottom: 16, borderRadius: 8, boxShadow: '0 1px 4px rgba(0,0,0,0.08)' };
  const sectionTitleStyle: React.CSSProperties = { fontSize: 13, fontWeight: 700, color: '#888', textTransform: 'uppercase', letterSpacing: 1, display: 'block', marginBottom: 8 };

  return (
    <AppContainer>
      {/* Header */}
      <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, gap: 12 }}>
        <div>
          <Title level={3} style={{ margin: 0 }}>Final Daily Report</Title>
          <Text style={{ color: '#888' }}>{selectedDate.format('DD MMMM YYYY')}</Text>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Button icon={<LeftOutlined />} onClick={handlePrevDay} />
          <DatePicker
            value={selectedDate}
            onChange={(d) => d && setSelectedDate(d)}
            format="DD-MM-YYYY"
            allowClear={false}
            style={{ width: 130 }}
          />
          <Button icon={<RightOutlined />} onClick={handleNextDay} disabled={selectedDate.isSame(dayjs(), 'day')} />
          <Button type="primary" icon={<FilePdfOutlined />} onClick={handleExportPdf} loading={pdfLoading}>
            Export PDF
          </Button>
        </div>
      </div>

      <Spin spinning={loading}>
        {reportData && (
          <div>

            {/* ── INCOME ── */}
            <Card title="Income" style={cardStyle}>
              {/* Quick Bill */}
              <Text style={sectionTitleStyle}>Quick Bill (Cash Bill)</Text>
              <Row2 label="Cash" value={`Rs. ${fmt(quickBill.cash)}`} />
              <Row2 label="Bank / UPI" value={`Rs. ${fmt(quickBill.bank)}`} />
              <TotalRow label="Quick Bill Total" value={`Rs. ${fmt(quickBill.total)}`} />

              <Divider style={{ margin: '16px 0' }} />

              {/* Credit Bills */}
              <Text style={sectionTitleStyle}>Credit Bills</Text>
              <Row2 label="Cash" value={`Rs. ${fmt(creditBill.cash)}`} />
              <Row2 label="Bank / UPI" value={`Rs. ${fmt(creditBill.bank)}`} />
              {creditBill.details.length > 0 && (
                <Table
                  dataSource={creditBill.details}
                  size="small"
                  pagination={false}
                  rowKey="invoiceNo"
                  style={{ marginTop: 8 }}
                  locale={{ emptyText: 'No credit bills today' }}
                  columns={[
                    { title: 'Customer', dataIndex: 'name', key: 'name' },
                    { title: 'Invoice No', dataIndex: 'invoiceNo', key: 'invoiceNo' },
                    { title: 'Date', dataIndex: 'date', key: 'date', render: (val: string) => dayjs(val).format('DD-MM-YYYY') },
                    { title: 'Cash (Rs.)', dataIndex: 'cash', key: 'cash', render: (val: number) => fmt(val) },
                    { title: 'Bank/UPI (Rs.)', dataIndex: 'bank', key: 'bank', render: (val: number) => fmt(val) },
                    { title: 'Total (Rs.)', dataIndex: 'amount', key: 'amount', render: (val: number) => fmt(val) },
                  ]}
                />
              )}
              <TotalRow label="Credit Bill Total" value={`Rs. ${fmt(creditBill.totalAmount)}`} />

              <Divider style={{ margin: '16px 0' }} />

              {/* Customer Payments */}
              <Text style={sectionTitleStyle}>Customer Payments</Text>
              <Row2 label="Cash" value={`Rs. ${fmt(customerPayment.cash)}`} />
              <Row2 label="Bank / UPI" value={`Rs. ${fmt(customerPayment.bank)}`} />
              <TotalRow label="Customer Payment Total" value={`Rs. ${fmt(customerPayment.cash + customerPayment.bank)}`} />

              <Divider style={{ margin: '16px 0' }} />

              {/* Grand Income */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', background: '#111', borderRadius: 6 }}>
                <Text style={{ color: '#fff', fontWeight: 700, fontSize: 15 }}>TOTAL INCOME</Text>
                <Text style={{ color: '#fff', fontWeight: 700, fontSize: 18 }}>Rs. {fmt(totalIncome)}</Text>
              </div>
            </Card>

            {/* ── OUTGOINGS ── */}
            <Card title="Outgoings" style={cardStyle}>
              {/* Supplier Payments */}
              <Text style={sectionTitleStyle}>Supplier Payments</Text>
              <Row2 label="Cash" value={`Rs. ${fmt(supplierPayment.cash)}`} />
              <Row2 label="Bank / UPI" value={`Rs. ${fmt(supplierPayment.bank)}`} />
              <TotalRow label="Supplier Payment Total" value={`Rs. ${fmt(supplierPayment.cash + supplierPayment.bank)}`} />

              <Divider style={{ margin: '16px 0' }} />

              {/* Expenses */}
              <Text style={sectionTitleStyle}>Expenses</Text>
              {expenses.details.length > 0 && (
                <Table
                  dataSource={expenses.details}
                  size="small"
                  pagination={false}
                  rowKey="id"
                  style={{ marginBottom: 8 }}
                  columns={[
                    { title: 'Category', dataIndex: 'category', key: 'category' },
                    { title: 'Mode', dataIndex: 'paymentMode', key: 'paymentMode' },
                    { title: 'Amount (Rs.)', dataIndex: 'amount', key: 'amount', render: (val: number) => fmt(val) },
                  ]}
                />
              )}
              <TotalRow label="Expenses Total" value={`Rs. ${fmt(expenses.total)}`} />

              <Divider style={{ margin: '16px 0' }} />

              {/* Grand Outgoings */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', background: '#111', borderRadius: 6 }}>
                <Text style={{ color: '#fff', fontWeight: 700, fontSize: 15 }}>TOTAL OUTGOINGS</Text>
                <Text style={{ color: '#fff', fontWeight: 700, fontSize: 18 }}>Rs. {fmt(totalOutgoings)}</Text>
              </div>
            </Card>

            {/* ── FINAL BALANCE ── */}
            <Card title="Final Balance" style={cardStyle}>
              <Row gutter={[16, 16]}>
                <Col xs={24} md={8} style={{ textAlign: 'center' }}>
                  <Text style={{ display: 'block', color: '#888', fontSize: 12, marginBottom: 4 }}>Cash in Hand</Text>
                  <Title level={4} style={{ margin: 0 }}>Rs. {fmt(finalBalances.cash)}</Title>
                </Col>
                <Col xs={24} md={8} style={{ textAlign: 'center' }}>
                  <Text style={{ display: 'block', color: '#888', fontSize: 12, marginBottom: 4 }}>Bank / UPI</Text>
                  <Title level={4} style={{ margin: 0 }}>Rs. {fmt(finalBalances.bank)}</Title>
                </Col>
                <Col xs={24} md={8} style={{ textAlign: 'center' }}>
                  <Text style={{ display: 'block', color: '#888', fontSize: 12, marginBottom: 4 }}>Net Total</Text>
                  <Title level={4} style={{ margin: 0 }}>Rs. {fmt(finalBalances.cash + finalBalances.bank)}</Title>
                </Col>
              </Row>
            </Card>

            {/* ── OUTSTANDING ── */}
            <Card title="Outstanding" style={cardStyle}>
              <Row gutter={[16, 16]}>
                <Col xs={24} md={12}>
                  <div style={{ border: '1px solid #d9d9d9', borderRadius: 6, padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <Text strong style={{ display: 'block', fontSize: 14 }}>Supplier Outstanding</Text>
                      <Text style={{ fontSize: 12, color: '#888' }}>Amount to Pay</Text>
                    </div>
                    <Title level={4} style={{ margin: 0 }}>Rs. {fmt(outstanding.supplier)}</Title>
                  </div>
                </Col>
                <Col xs={24} md={12}>
                  <div style={{ border: '1px solid #d9d9d9', borderRadius: 6, padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <Text strong style={{ display: 'block', fontSize: 14 }}>Customer Outstanding</Text>
                      <Text style={{ fontSize: 12, color: '#888' }}>Amount to Receive</Text>
                    </div>
                    <Title level={4} style={{ margin: 0 }}>Rs. {fmt(outstanding.customer)}</Title>
                  </div>
                </Col>
              </Row>
            </Card>

            {/* ── PURCHASES ── */}
            <Card title="Purchase Details" style={cardStyle}>
              <Table
                dataSource={purchases.details}
                size="small"
                pagination={false}
                rowKey="id"
                locale={{ emptyText: 'No purchases today' }}
                columns={[
                  { title: 'Item', dataIndex: 'vegetableName', key: 'vegetableName' },
                  { title: 'Qty', dataIndex: 'qty', key: 'qty' },
                  { title: 'Rate (Rs.)', dataIndex: 'rate', key: 'rate' },
                  { title: 'Total (Rs.)', dataIndex: 'total', key: 'total', render: (val: number) => fmt(val) },
                ]}
              />
              <TotalRow label="Total Purchases" value={`Rs. ${fmt(purchases.total)}`} />
            </Card>

          </div>
        )}
      </Spin>
    </AppContainer>
  );
};
