import { DomesticSalesReqDto } from '@gtpl/shared-models/sale-management';
import { SaleOrderService } from '@gtpl/shared-services/sale-management'
import { Button, Card, Input, message, Modal, Table } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom';
import DomesticSalesForm from './domestic-sales-form';
import { ColumnProps } from 'antd/lib/table';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import Highlighter from 'react-highlight-words';
import { SearchOutlined, UndoOutlined } from "@ant-design/icons";

const DomesticSalesGrid = () => {
    const saleOrderService = new SaleOrderService();
    const [domesticSalesData, setDomesticSalesData] = useState();
    const [selectDomesticSalesForm, setselectDomesticSalesForm] = useState<number>( );
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);

    useEffect(() => {
        getData();
    }, []);

    const getData = () => {
        saleOrderService.getDomesticSalesGrid().then(res => {
            if (res.status) {
                setDomesticSalesData(res.data);
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    };

    function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
    };
    const getColumnSearchProps = (dataIndex: string) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
            <div style={{ padding: 8 }}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ width: 188, marginBottom: 8, display: 'block' }}
                />
                <Button
                    type="primary"
                    onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    icon={<SearchOutlined />}
                    size="small"
                    style={{ width: 90, marginRight: 8 }}
                >
                    Search
                </Button>
                <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                    Reset
                </Button>
            </div>
        ),
        filterIcon: filtered => (
            <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
            record[dataIndex]
                ? record[dataIndex]
                    .toString()
                    .toLowerCase()
                    .includes(value.toLowerCase())
                : false,
        onFilterDropdownVisibleChange: visible => {
            if (visible) { setTimeout(() => searchInput.current.select()); }
        },
        render: text =>
            text ? (
                searchedColumn === dataIndex ? (
                    <Highlighter
                        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                        searchWords={[searchText]}
                        autoEscape
                        textToHighlight={text.toString()}
                    />
                ) : text
            ) : null
    });


    const columns: ColumnProps<any>[] = [
        {
          title: "Product",
          dataIndex: "productName",
          ...getColumnSearchProps('productName')
        },
        // {
        //   title: "Pack Style",
        //   dataIndex: "packStyle",
        //   ...getColumnSearchProps('packStyle')
        // },
        {
          title: "Cases",
          dataIndex: "cases",
          ...getColumnSearchProps('cases')
        },
        {
          title: "Loose Pouches",
          dataIndex: "loosePouches",
          ...getColumnSearchProps('loosePouches')
        },
        {
          title: "Quantity (In Kgs)",
          dataIndex: "quantity",
          // render: (text) => {
          //   const quantity = parseFloat(text);
          //   const indianFormattedNumber = quantity.toLocaleString('en-IN', {
          //     minimumFractionDigits: 2,
          //     maximumFractionDigits: 2
          //   });
          //   const formattedText = quantity.toFixed(2).replace(/\.?0+$/, '');
          //   return (
          //     <>
          //       <div>{indianFormattedNumber}</div>
          //       {/* <div>{formattedText}</div> */}
          //     </>
          //   );
          // },
        
          sorter: (a, b) => parseFloat(a.quantity) - parseFloat(b.quantity),
          sortDirections: ['ascend', 'descend'],
          ...getColumnSearchProps('quantity'),
          render: (text, record) => {
            const qty = Number(record.quantity); 
            return !isNaN(qty)
                ? qty % 1 === 0 
                    ? qty.toFixed(0) 
                    : qty.toFixed(2) 
                : '-';
        },
        },
        
        {
          title: "Action",
          render: (text, record) => {
            const handleCreateSale = () => {
              const quantity = parseFloat(record.quantity);
              if (quantity === 0) {
                message.error('Cannot create sale of quantity 0');
              } else {
                displayForm(record.varientId);
              }
            };
      
            return (
              <Button type="primary" onClick={handleCreateSale}>
                Create sale
              </Button>
            );
          }
        }
      ];

    
    const displayForm = (data: number) => {
        console.log(data,"varientdataGrid")
        setselectDomesticSalesForm(data);
        setIsModalVisible(true);
      };

      const handleFormSubmitSuccess = () => {
        setIsModalVisible(false); 
        getData(); 
    };

    return (
        <div>
            <Card title={<span style={{ color: 'white' }}>Domestic Sales</span>} style={{ textAlign: "center" }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
             extra={
                <Link to="/domestic-sales-view">
                    <Button 
                        type="primary" 
                        style={{ background: "white", color: "#3C085C" }}
                    >
                        View
                    </Button>
                </Link>
            }
            >
                <Table columns={columns} dataSource={domesticSalesData} />
                <Modal visible={isModalVisible} onCancel={() => setIsModalVisible(false)} width={'100%'} footer={[]} key={selectDomesticSalesForm}>
                <DomesticSalesForm varientId={selectDomesticSalesForm} onSubmitSuccess={handleFormSubmitSuccess}/>
            </Modal>
            </Card>
        </div>
    )
}

export default DomesticSalesGrid;
