import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Row, Table, Tooltip, Select, Input } from 'antd';
import { FilePdfOutlined, SearchOutlined } from '@ant-design/icons';
import { SaleOrderService } from 'libs/shared-services/sale-management/src/lib/saleorder-services';
import { GrnService } from '../../../../../../shared-services/procurement/src/lib/grn-service';
import { PurchaseOrderService } from '../../../../../../shared-services/procurement/src/lib/purchase-order.service';
import appSettings from 'apps/services/config';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Link } from 'react-router-dom';
import Highlighter from 'react-highlight-words';

const { Option } = Select;

export const TallyView = () => {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [filterType, setFilterType] = useState('invoice'); // Add state to track filter type
  const [data, setData] = useState<any[]>([]);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  
  const service = new SaleOrderService();
  const grnService = new GrnService();
  const poNumberService = new PurchaseOrderService();

  useEffect(() => {
    fetchData();
  }, [filterType]); // Fetch data when filterType changes

  const fetchData = () => {
    if (filterType === 'invoice') {
      service.getInvoiceNumberData().then((res) => {
        if (res.status) {
          setData(res.data);
        }
      });
    } else if (filterType === 'grn') {
      grnService.getGrnData().then((res) => {
        if (res.status) {
          setData(res.data);
        }
      });
    } else if (filterType === 'po') {
      poNumberService.getPoNumberData().then((res) => {
        if (res.status) {
          setData(res.data);
        }
      });
    }
  };
  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 download = (filePath: string) => {
    if (!filePath) {
      AlertMessages.getErrorMessage('Please upload file.');
      return;
    }
  
    // Determine the base directory according to the filter type
    let baseDirectory = '';
    switch (filterType) {
      case 'invoice':
        baseDirectory = 'invoice-files';
        break;
      case 'grn':
        baseDirectory = 'grn-files';
        break;
      case 'po':
        baseDirectory = 'po-files';
        break;
      default:
        AlertMessages.getErrorMessage('Invalid file type.');
        return;
    }
  
    // Split and download each file in the list
    const files = filePath.split(',');
    files.forEach((file) => {
      if (file.trim()) {
        setTimeout(() => {
          const response = {
            file: `${appSettings.tally_upload_files}/${baseDirectory}/${file.trim()}`,
          };
          window.open(response.file);
        }, 100);
      }
    });
  };
  
const columns : any[] = [
    {
      title: 'S No',
      key: 'sNo',
      responsive: ['sm'],
      render: (text: any, object: any, index: number) =>
        (page - 1) * pageSize + (index + 1) + pageSize * (page - 1),
    },
    {
      title: filterType === 'po' ? 'PO Number' : 'Invoice Number',
      dataIndex: filterType === 'po' ? 'po_number' : filterType === 'grn' ? 'inv_no' : 'invoice_number',
      ...getColumnSearchProps(filterType === 'po' ? 'po_number' : filterType === 'grn' ? 'inv_no' : 'invoice_number'),

    },
    {
      title: 'File Name',
      dataIndex: 'file_name',
      ...getColumnSearchProps('file_name')
    },
    {
      title: 'File View',
      dataIndex: 'file_view',
      align: 'center',
      width: 120,
      render: (value: any, record: any) => (
        <Tooltip title="PDF download">
          <Button
            icon={<FilePdfOutlined onClick={() => download(record.file_name)} style={{ color: 'red' }} />}
          >
            {value}
          </Button>
        </Tooltip>
      ),
    },
  ];


  return (
    <Card
      title={<span style={{ color: 'white' }}>Tally File View</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      extra={
        <Link to='/tally-upload-files'>
          <span style={{ color: 'white' }}>
            <Button className='panel_button'>Back</Button>
          </span>
        </Link>
      }
    >
      <Row justify="space-between" align="middle">
        {/* Filter select */}
        <Select
          value={filterType}
          onChange={(value) => setFilterType(value)}
          style={{ width: 200 }}
        >
          <Option value="invoice">Invoice</Option>
          <Option value="grn">GRN</Option>
          <Option value="po">PO</Option>
        </Select>
      </Row>
  
      <Table
        className="custom-table-wrapper"
        columns={columns}
        dataSource={data}
        size="small"
        pagination={{
          pageSize: 100,
          onChange(current, pageSize) {
            setPage(current);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
  
};

export default TallyView;