import { useEffect, useState } from 'react';
import {
    Button,
    DatePicker,
    Space,
    Table,
    Tag,
    message,
    Spin,
    Typography,
} from 'antd';
import {
    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 { RangePicker } = DatePicker;
const { Text } = Typography;

interface LedgerRow {
    key: string;
    date: string | null;
    voucherNo: string;
    customerName: string;
    transactionType: string;
    description: string;
    debit: number;
    credit: number;
}

const TYPE_COLORS: Record<string, string> = {
    'Sale': 'blue',
    'Receipt': 'green',
    'Payment': 'red',
    'Sales Return': 'orange',
};

const WalkInLedger = () => {
    const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
    const [data, setData] = useState<LedgerRow[]>([]);
    const [loading, setLoading] = useState(false);
    const [totalDebit, setTotalDebit] = useState(0);
    const [totalCredit, setTotalCredit] = useState(0);

    const fetchData = async (range: [Dayjs, Dayjs] | null = dateRange) => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            if (range) {
                params.set('dateFrom', range[0].format('YYYY-MM-DD'));
                params.set('dateTo', range[1].format('YYYY-MM-DD'));
            }

            const res = await jwtAxios.get(`${ENDPOINTS.WALK_IN_LEDGER}?${params.toString()}`);
            const rows: LedgerRow[] = (res.data?.result?.entries || []).map((r: any, i: number) => ({
                key: `${i}`,
                date: r.date,
                voucherNo: r.voucherNo,
                customerName: r.customerName,
                transactionType: r.transactionType,
                description: r.description,
                debit: Number(r.debit ?? 0),
                credit: Number(r.credit ?? 0),
            }));
            setData(rows);

            let tDebit = 0;
            let tCredit = 0;
            rows.forEach((r) => {
                tDebit += r.debit;
                tCredit += r.credit;
            });
            setTotalDebit(tDebit);
            setTotalCredit(tCredit);
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to fetch ledger data');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        const from = dayjs().startOf('month');
        const to = dayjs().endOf('month');
        const range: [Dayjs, Dayjs] = [from, to];
        setDateRange(range);
        fetchData(range);
    }, []);

    const handleReset = () => {
        const from = dayjs().startOf('month');
        const to = dayjs().endOf('month');
        const range: [Dayjs, Dayjs] = [from, to];
        setDateRange(range);
        fetchData(range);
    };

    const handleDateRangeChange = (values: any) => {
        const range = values ? (values as [Dayjs, Dayjs]) : null;
        setDateRange(range);
        fetchData(range);
    };

    const columns = [
        {
            title: 'Date',
            dataIndex: 'date',
            width: 110,
            render: (val: string | null) => val ? dayjs(val).format('DD/MM/YYYY') : <Text type="secondary">—</Text>,
        },
        {
            title: 'Voucher No',
            dataIndex: 'voucherNo',
            width: 140,
            render: (val: string) => <Text strong>{val}</Text>,
        },
        {
            title: 'Walk-In Name',
            dataIndex: 'customerName',
            width: 180,
            render: (val: string) => val || <Text type="secondary">—</Text>,
        },
        {
            title: 'Type',
            dataIndex: 'transactionType',
            width: 130,
            render: (type: string) => (
                <Tag color={TYPE_COLORS[type] ?? 'default'}>{type}</Tag>
            ),
        },
        {
            title: 'Description',
            dataIndex: 'description',
            ellipsis: true,
        },
        {
            title: 'Debit (₹)',
            dataIndex: 'debit',
            width: 120,
            align: 'right' as const,
            render: (val: number) => val > 0
                ? <Text style={{ color: '#d46b08', fontWeight: 600 }}>{val.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</Text>
                : <Text type="secondary">—</Text>,
        },
        {
            title: 'Credit (₹)',
            dataIndex: 'credit',
            width: 120,
            align: 'right' as const,
            render: (val: number) => val > 0
                ? <Text style={{ color: '#389e0d', fontWeight: 600 }}>{val.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</Text>
                : <Text type="secondary">—</Text>,
        },
    ];

    return (
        <div>
            <Spin spinning={loading}>
                <AppContainer title="Walk-In Ledger">
                    {/* Filters */}
                    <div style={{ marginBottom: 16 }}>
                        <Space wrap>
                            <RangePicker value={dateRange as any} onChange={handleDateRangeChange} />
                            <Button type="default" icon={<RedoOutlined />} onClick={handleReset}>
                                Reset
                            </Button>
                        </Space>
                    </div>

                    {/* Ledger Table */}
                    <Table
                        columns={columns}
                        dataSource={data}
                        loading={loading}
                        rowKey="key"
                        pagination={false}
                        rowClassName={(row: LedgerRow) => {
                            if (row.debit > 0) return 'ledger-row-debit';
                            if (row.credit > 0) return 'ledger-row-credit';
                            return '';
                        }}
                        scroll={{ x: 900 }}
                        size="small"
                        summary={() => (
                            <Table.Summary fixed>
                                <Table.Summary.Row>
                                    <Table.Summary.Cell index={0} colSpan={5}>
                                        <Text strong>Total</Text>
                                    </Table.Summary.Cell>
                                    <Table.Summary.Cell index={5} align="right">
                                        <Text strong style={{ color: '#d46b08' }}>
                                            {totalDebit.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                                        </Text>
                                    </Table.Summary.Cell>
                                    <Table.Summary.Cell index={6} align="right">
                                        <Text strong style={{ color: '#389e0d' }}>
                                            {totalCredit.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                                        </Text>
                                    </Table.Summary.Cell>
                                </Table.Summary.Row>
                            </Table.Summary>
                        )}
                    />
                </AppContainer>
            </Spin>

            <style>{`
                .ledger-row-debit td { background-color: #fff9f0 !important; }
                .ledger-row-credit td { background-color: #f6ffed !important; }
            `}</style>
        </div>
    );
};

export default WalkInLedger;
