import React from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Card } from 'primereact/card';

interface CanvasData {
    [key: string]: any;
}

interface CanvasDataTableProps {
    data: CanvasData[];
    loading: boolean;
    error: string | null;
}

const CanvasDataTable: React.FC<CanvasDataTableProps> = ({
    data,
    loading,
    errorimport { Column } from 'primereact/column';
    import { FilterMatchMode, FilterOperator } from 'primereact/api';
    import { useEffect, useRef, useState } from 'react';
    import { api } from '../../services/api.ts';
    
    import TableGroupHeader from '../../shared/components/_V1/TableGroupHeader.tsx';
    import TableGroup from '../../shared/components/_V1/TableGroup.tsx';
    
    import { Toast } from 'primereact/toast';
    import ConfirmModal from '../../shared/components/modals/ConfirmModal.tsx';
    import CreateVoucherModal from './CreateVoucherModal.tsx';
    // import EditVoucherModal from './AddVoucherCodeModal.tsx';
    import LoadingPage from '../../shared/components/_V1/LoadingPage.tsx';
    import DetailModal from './DetailModal.tsx';
    import AddVoucherCodeModal, { AddVoucherCodeModalProps } from './AddVoucherCodeModal.tsx';
    import { Voucher, useVoucherStore } from '../../state/stores/Mews/useMewsVoucherStore.ts';
    import { TSizeOptionValue } from '../../types/DataTable.types.ts';
    import Button from '../../shared/components/_V2/Button.tsx';
    
    export default function VoucherTableGroup() {
      const { createVoucher, fetchVouchers, updateVoucher, vouchers, addVoucherCode } =
        useVoucherStore();
    
      const [filters, setFilters] = useState(null);
      const [globalFilterValue, setGlobalFilterValue] = useState('');
    
      const [showCreateVoucherModal, setShowCreateVoucherModal] = useState(false);
      const [showConfirmDeleteModal, setShowConfirmDeleteModal] = useState(false);
    
      const [showAddCodeModal, setShowAddCodeModal] = useState(false);
      const [currentVoucherForCode, setCurrentVoucherForCode] = useState(null);
    
      const [detailModalVisible, setDetailModalVisible] = useState(false);
      const [detailContent, setDetailContent] = useState([]);
      const [detailTitle, setDetailTitle] = useState('');
    
      const [selectedVouchers, setSelectedVouchers] = useState<Voucher[]>(null);
    
      const toast = useRef<Toast>(null);
    
      const [isLoading, setIsLoading] = useState(false);
    
      // Change table row size
      const sizeOptions: { label: string; value: TSizeOptionValue }[] = [
        { label: 'Small', value: 'small' },
        { label: 'Normal', value: 'normal' },
        { label: 'Large', value: 'large' },
      ];
    
      const [size, setSize] = useState<TSizeOptionValue>(sizeOptions[0].value);
    
      useEffect(() => {
        initFilters();
        // fetchVouchers;
        handleRefresh();
      }, []);
    
      const showToastMessage = (options) => {
        toast.current?.show(options);
      };
    
      const initFilters = () => {
        setFilters({
          global: { value: null, matchMode: FilterMatchMode.CONTAINS },
          representative: { value: null, matchMode: FilterMatchMode.IN },
          createdAt: {
            operator: FilterOperator.AND,
            constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }],
          },
        });
        setGlobalFilterValue('');
      };
    
      const clearFilter = () => {
        initFilters();
      };
    
      const onGlobalFilterChange = (e: { target: { value: any } }) => {
        const value = e.target.value;
        // @ts-ignore
        let _filters = { ...filters };
        _filters['global'].value = value;
        setFilters(_filters);
        setGlobalFilterValue(value);
      };
    
      // TODO: refresh data
      const handleRefresh = async () => {
        setIsLoading(true);
        await fetchVouchers();
        setIsLoading(false);
      };
    
      const formatDate = (value: string | number | Date) => {
        const date = new Date(value);
        return date.toLocaleDateString('en-US', {
          day: '2-digit',
          month: '2-digit',
          year: 'numeric',
        });
      };
    
      const dateBodyTemplate = (rowData: { createdAt: string | number | Date }) => {
        return formatDate(rowData.createdAt);
      };
    
      const actionButtons = () => {
        return (
          <div className={'flex gap-3'}>
            <Button text={true} onClick={() => setShowCreateVoucherModal(true)}>
              Add Voucher
            </Button>
            {/* <Button
              onClick={() => setShowConfirmDeleteModal(true)}
              severity={'danger'}
              disabled={selectedVouchers == null || selectedVouchers.length === 0}
            >
              Delete selected
            </Button> */}
          </div>
        );
      };
    
      const editButton = (rowData: Voucher) => {
        return <Button>action</Button>;
      };
    
      const openDetailModal = (content, title) => {
        setDetailContent(content);
        setDetailTitle(title);
        setDetailModalVisible(true);
      };
    
      const closeDetailModal = () => {
        setDetailModalVisible(false);
      };
    
      const handleCreateVoucher = async (newVoucher: Voucher) => {
        await createVoucher(newVoucher);
        handleRefresh();
        setShowCreateVoucherModal(false);
      };
    
      const handleDeleteSelectedVouchers = () => {
        const URL = '/neppeURL';
        const body = selectedVouchers.map((voucher) => {
          return {
            id: voucher.id,
          };
        });
        api('delete', URL, body);
      };
    
      const voucherRatesBodyTemplate = (rowData) => {
        if (rowData?.voucherCodes.length < 1) {
          return '';
        }
        const details = rowData.rates.map((rate) => `Name: ${rate.name}, Type: ${rate.type}`);
        return (
          <Button
            label='View Rates'
            onClick={() => openDetailModal(details, 'Voucher Rates')}
            disabled={isLoading}
          />
        );
      };
    
      const voucherCodesBodyTemplate = (rowData) => {
        const details = rowData.voucherCodes.join(', ');
        return (
          <div className='flex gap-2'>
            <Button
              label='View Codes'
              onClick={() => openDetailModal([details], 'Voucher Codes')}
              disabled={isLoading || rowData.voucherCodes.length === 0}
            />
            <Button
              label='Add Code'
              onClick={() => {
                setCurrentVoucherForCode(rowData);
                setShowAddCodeModal(true);
              }}
              disabled={isLoading}
            />
          </div>
        );
      };
    
      const handleAddVoucherCode: AddVoucherCodeModalProps['addVoucherCode'] = async (
        voucherId,
        code
      ) => {
        try {
          await addVoucherCode(voucherId, code);
          showToastMessage({
            severity: 'success',
            summary: 'Code Added',
            detail: 'Voucher code has been successfully added.',
          });
          setShowAddCodeModal(false);
          handleRefresh();
        } catch (error) {
          showToastMessage({
            severity: 'error',
            summary: 'Error',
            detail: 'Failed to add voucher code.',
          });
          console.error('Failed to add voucher code:', error);
        }
      };
    
      const renderHeader = () => {
        return (
          <TableGroupHeader
            size={size}
            setSize={setSize}
            sizeOptions={sizeOptions}
            globalFilterValue={globalFilterValue}
            onGlobalFilterChange={(e: any) => onGlobalFilterChange(e)}
            onRefresh={handleRefresh}
            clearFilter={clearFilter}
          />
        );
      };
    
      const voucherCodeSortFunction = (e) => {
        const result = e.data.sort((data1, data2) => {
          const codes1 = data1.voucherCodes.length;
          const codes2 = data2.voucherCodes.length;
    
          return e.order * (codes1 - codes2);
        });
        return result;
      };
    
      return (
        <div className='w-full h-full flex flex-col'>
          <CreateVoucherModal
            visible={showCreateVoucherModal}
            onHide={() => setShowCreateVoucherModal(false)}
            // @ts-ignore
            onConfirm={handleCreateVoucher}
          />
    
          <AddVoucherCodeModal
            visible={showAddCodeModal}
            onHide={() => setShowAddCodeModal(false)}
            addVoucherCode={handleAddVoucherCode} // Pass the function directly
            voucherId={currentVoucherForCode?.id || ''}
          />
    
          <ConfirmModal
            visible={showConfirmDeleteModal}
            header={`Delete ${selectedVouchers?.length} voucher(s)`}
            message={`Are you sure?`}
            onHide={() => setShowConfirmDeleteModal(false)}
            onConfirm={handleDeleteSelectedVouchers}
            confirmLabel={'Confirm'}
            cancelLabel={'Cancel'}
            onCancel={() => setShowConfirmDeleteModal(false)}
          />
    
          <DetailModal
            visible={detailModalVisible}
            onHide={closeDetailModal}
            title={detailTitle}
            details={detailContent}
          />
    
          {isLoading ? (
            <LoadingPage />
          ) : (
            <TableGroup
              body={vouchers}
              size={size}
              header={renderHeader}
              filters={filters}
              rows={10}
              paginator
              // stripedRows={true}
              showGridlines={true}
              removableSort={true}
              dragSelection={false}
              selectionMode={'multiple'}
              selection={selectedVouchers}
              onSelectionChange={(e: any) => setSelectedVouchers(e.value)}
              emptyMessage='No vouchers found.'
            >
              <Column selectionMode='multiple' headerStyle={{ width: '3rem' }}></Column>
    
              <Column field='id' header={actionButtons} sortable filter style={{ width: '40%' }} />
              <Column field='name' header='Name' sortable filter style={{ width: '20%' }} />
              <Column field='type' header='Type' sortable filter style={{ width: '20%' }} />
              <Column
                field='voucherCodes'
                header='Voucher Codes'
                body={voucherCodesBodyTemplate}
                sortable
                filter
                sortFunction={voucherCodeSortFunction}
                className='h-full align-top bg-red'
                style={{ width: '20%', textAlign: 'center', lineHeight: '20px' }}
              />
              <Column
                field='rates'
                header='Voucher Rates'
                body={voucherRatesBodyTemplate}
                sortable
                filter
                style={{ width: '20%' }}
              />
              {/* <Column
                field='actions'
                header='Actions'
                body={editButton}
                style={{ width: '15%', textAlign: 'center' }}
              /> */}
            </TableGroup>
          )}
        </div>
      );
    }
    
}) => {
    // Dynamically generate columns based on the first data item
    const columns = data.length > 0
        ? Object.keys(data[0]).map(key => (
            <Column
                key={key}
                field={key}
                header={key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' ')}
                sortable
            />
        ))
        : [];

    return (
        <Card className="flex-grow mb-4">
            <DataTable
                value={data}
                loading={loading}
                emptyMessage={error || "No data found. Try using the prompt below."}
                className="p-datatable-sm"
                paginator
                rows={10}
                rowsPerPageOptions={[10, 25, 50]}
            >
                {columns}
            </DataTable>
        </Card>
    );
};

export default CanvasDataTable; 