import { Switch, Tooltip } from 'antd';
import { useDispatch } from 'react-redux';
import {
  changeBillName,
  changeNotes,
  changeSelectedAmount,
  changeSelectedDiscount,
  changeSelectedHsnCode,
  changeSelectedItem,
  changeSelectedMRP,
  changeSelectedprintStyle,
  changeSelectedQrcode,
  changeSelectedQuantity,
  changeSelectedRate,
  changeSelectedSignature,
  changeSelectedSlNo,
  changeSelectedtermsAndConditions,
  changeSignatureImage,
  changethemeFormat,
  getPrintSelectionComponentData,
  putPrintSelectionComponentData,
  changeSelectedPrintdummyData,
} from '../../../../Features/ThemeChange/ThemeChange';
import { useEffect, useState, useMemo, useCallback } from 'react';
import {
  InfoCircleOutlined,
  UploadOutlined,
  PlusOutlined,
  MinusCircleOutlined,
  ArrowRightOutlined,
  EditFilled,
  DeleteFilled,
} from '@ant-design/icons';
import { getSession } from '../../../../Services/Others';
import Buttons from '../../../../Components/Forms/Buttons';
import { Messages } from '../../../../Components/Notifications/Messages';

const SalesPrintSize = ({ onSettingsChange, closeModel }) => {
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const dispatch = useDispatch();

  const [PrintType, setPrintType] = useState(false);
  const [PageSize, setPageSize] = useState(false);
  // const [PrintTemplates, setPrintTemplates] = useState([])
  const [SizeOptionData, setSizeOptionData] = useState([]);
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [messageType, setMessageType] = useState('');
  const [messageData, setMessageData] = useState('');
  console.log(selectedTemplate, 'selectedTemplate');

  // Memoized values for better performance
  const currentPrintType = useMemo(() => {
    if (selectedTemplate) {
      return selectedTemplate.PrintType === 'S' ? true : false;
    }
    return PrintType;
  }, [selectedTemplate, PrintType]);

  const currentPageSize = useMemo(() => {
    if (selectedTemplate) {
      return selectedTemplate.PageSize === 'A5' ? true : false;
    }
    return PageSize;
  }, [selectedTemplate, PageSize]);

  // Get the actual values to pass to parent component
  const getPrintTypeValue = () => {
    if (selectedTemplate) {
      return selectedTemplate.PrintType;
    }
    return PrintType ? 'S' : 'C';
  };

  const getPageSizeValue = () => {
    if (selectedTemplate) {
      return selectedTemplate.PageSize;
    }
    return PageSize ? 'A5' : 'A4';
  };

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

  // Auto-select default template when data loads
  useEffect(() => {
    if (SizeOptionData.length > 0) {
      const defaultTemplate = SizeOptionData.find(
        (template) => template.SetasDefault === 'Y'
      );
      if (defaultTemplate) {
        handleTemplateSelect(defaultTemplate);
      }
    }
  }, [SizeOptionData]);

  const handleTemplateSelect = (template) => {
    setSelectedTemplate(template);
    setPrintType(template.PrintType === 'S');
    setPageSize(template.PageSize === 'A5');
    stylePreview(template);

    // Immediately pass the template settings
    if (onSettingsChange && typeof onSettingsChange === 'function') {
      const currentSettings = {
        PrintType: template.PrintType,
        PageSize: template.PageSize,
        selectedTemplate: template,
      };
      console.log('Template Selected - Settings:', currentSettings);
      onSettingsChange(currentSettings);
    }
  };

  const onChangeToggle = async (e) => {
    setPrintType(e);
    await dispatch(changethemeFormat(e));

    // If a template is selected, update it
    if (selectedTemplate) {
      const updatedTemplate = {
        ...selectedTemplate,
        PrintType: e ? 'S' : 'C',
      };
      setSelectedTemplate(updatedTemplate);

      // Immediately pass updated settings
      if (onSettingsChange && typeof onSettingsChange === 'function') {
        const currentSettings = {
          PrintType: updatedTemplate.PrintType,
          PageSize: updatedTemplate.PageSize,
          selectedTemplate: updatedTemplate,
        };
        onSettingsChange(currentSettings);
      }
    }
  };

  const onChangepageSize = async (e) => {
    setPageSize(e);

    // If a template is selected, update it
    if (selectedTemplate) {
      const updatedTemplate = {
        ...selectedTemplate,
        PageSize: e ? 'A5' : 'A4',
      };
      setSelectedTemplate(updatedTemplate);
      if (onSettingsChange && typeof onSettingsChange === 'function') {
        const currentSettings = {
          PrintType: updatedTemplate.PrintType,
          PageSize: updatedTemplate.PageSize,
          selectedTemplate: updatedTemplate,
        };
        onSettingsChange(currentSettings);
      }
    }
  };

  const stylePreview = async (template) => {
    if (!template) return;

    const {
      StyleId,
      StyleName,
      PrintType: printType,
      PageSize,
      Notes,
      PrintHdrName,
      Signature,
      TermsandConditions,
      OptionDetails,
    } = template;

    const helperFunction = (param) => {
      return OptionDetails.some((item) => item.ConfigName === param);
    };

    dispatch(changeSelectedSlNo(helperFunction('Sl.No')));
    dispatch(changeSelectedItem(helperFunction('Item')));
    dispatch(changeSelectedMRP(helperFunction('MRP')));
    dispatch(changeSelectedDiscount(helperFunction('Discount')));
    dispatch(changeSelectedQuantity(helperFunction('Quantity')));
    dispatch(changeSelectedRate(helperFunction('Rate')));
    dispatch(changeSelectedAmount(helperFunction('Amount')));
    dispatch(changeSelectedHsnCode(helperFunction('HsnCode')));
    dispatch(changeSelectedQrcode(helperFunction('Qrcode')));
    dispatch(changeSelectedSignature(helperFunction('signature')));
    dispatch(
      changeSelectedtermsAndConditions(helperFunction('terms&conditions'))
    );
    dispatch(changeNotes(helperFunction('Notes')));
    dispatch(changeSignatureImage(Signature));
    dispatch(changeBillName(PrintHdrName));
    dispatch(
      changeSelectedprintStyle({
        ConfigId: StyleId,
        ConfigName: StyleName,
      })
    );
  };

  const printsyleget = async () => {
    try {
      const Data = { AppId, CompId, BranchId };
      let response = await dispatch(
        getPrintSelectionComponentData(Data)
      ).unwrap();

      if (response?.data?.statusCode === 1) {
        // const salesTemplates = response.data.data?.flatMap(template =>
        //     (template.ComponentDetails || []).filter(comp => comp.PrintTypeName === "Sales" && comp.SetasDefault === "Y")
        // );
        // setPrintTemplates(salesTemplates);

        let TableData = response?.data?.data?.[0]?.ComponentDetails.map(
          (item) => ({
            ActiveStatus: 'A',
            OptionDetails: item.FieldDetails,
            StyleId: item.StyleId,
            SetasDefault: item.SetasDefault,
            SetasDefaultInvoice: item.SetasDefaultInvoice,
            StyleName: item.StyleName,
            Signature: item.Signature,
            PrintType: item.PrintType,
            PrintHdrName: item.PrintHdrName,
            Notes: item?.Notes,
            PageSize: item?.PageSize,
            PrintTypeId: item?.PrintTypeId,
            TermsandConditions: (item?.TermsandConditions
              ? item?.TermsandConditions
              : []
            )?.map((tc) => tc?.TermsandConditions),
          })
        )?.sort((a, b) => {
          if ((a.StyleName || '') === 'A4Standard') return 1;
          if ((b.StyleName || '') === 'A4Standard') return -1;
          const isA4orA5 = (name) => /A4|A5/i.test(name);
          const nameA = a.StyleName || '';
          const nameB = b.StyleName || '';
          if (isA4orA5(nameA) && !isA4orA5(nameB)) return 1;
          if (!isA4orA5(nameA) && isA4orA5(nameB)) return -1;
          const numA = parseInt(nameA.match(/\d+/)?.[0]) || 0;
          const numB = parseInt(nameB.match(/\d+/)?.[0]) || 0;
          return numA - numB;
        });
        setSizeOptionData(TableData);
      }
    } catch (error) {
      console.error('Error fetching print styles:', error);
    }
  };

  // Log current values for debugging
  console.log('Current PrintType:', getPrintTypeValue());
  console.log('Current PageSize:', getPageSizeValue());
  console.log('Selected Template:', selectedTemplate);

  useEffect(() => {
    const currentSettings = {
      PrintType: getPrintTypeValue(),
      PageSize: getPageSizeValue(),
      selectedTemplate,
    };
    console.log('Current Print Settings:', currentSettings);

    // Call the callback if provided
    if (onSettingsChange && typeof onSettingsChange === 'function') {
      onSettingsChange(currentSettings);
    }
  }, [selectedTemplate, PrintType, PageSize]); // Removed onSettingsChange from dependencies

  // Also pass data when component mounts and when selectedTemplate changes
  useEffect(() => {
    if (
      selectedTemplate &&
      onSettingsChange &&
      typeof onSettingsChange === 'function'
    ) {
      const currentSettings = {
        PrintType: selectedTemplate.PrintType,
        PageSize: selectedTemplate.PageSize,
        selectedTemplate,
      };
      console.log('Template-based Print Settings:', currentSettings);
      onSettingsChange(currentSettings);
    }
  }, [selectedTemplate]);

  const onfinish = async (values) => {
    try {
      if (!SizeOptionData || SizeOptionData.length === 0) {
        setMessageType('error');
        setMessageData('Please Setup the Screen');
        return;
      }

      if (!selectedTemplate) {
        setMessageType('error');
        setMessageData('Please select a template first');
        return;
      }

      const currentPrintType = getPrintTypeValue(); // 'S' or 'C'
      const currentPageSize = getPageSizeValue(); // 'A4' or 'A5'

      // Only one "Sales" style should have SetasDefault: "Y"
      const updatedTemplates = SizeOptionData.map((item) => {
        if (item.PrintType === 'Sales' || item.PrintType === 'S') {
          return {
            ...item,
            SetasDefault: item.StyleId === selectedTemplate.StyleId ? 'Y' : 'N',
          };
        }
        return item;
      });

      let TemplateDetails = updatedTemplates.map((item) => {
        const isSelectedTemplate = item.StyleId === selectedTemplate.StyleId;

        return {
          SizeId: null,
          StyleId: item.StyleId,
          SetasDefault: item.SetasDefault,
          SetasDefaultInvoice: item.SetasDefaultInvoice,
          PrintTypeId: item?.PrintTypeId,
          SizeDetails: item.OptionDetails.map((opt) => ({
            OptionId: opt.ConfigId,
          })),
          ...(item?.TermsandConditions?.length > 0
            ? {
                PrintTermsandConditions: (item?.TermsandConditions
                  ? item?.TermsandConditions
                  : []
                )?.map((tc) => ({
                  TermsandConditions: tc,
                })),
              }
            : {}),
          ...(item?.Notes ? { Notes: item.Notes } : {}),
          PageSize: isSelectedTemplate ? currentPageSize : item?.PageSize,
          ...(item?.PrintHdrName ? { PrintHdrName: item.PrintHdrName } : {}),
          ...(item?.Signature ? { Signature: item?.Signature } : {}),
          PrintType: isSelectedTemplate ? currentPrintType : item?.PrintType,
        };
      });

      const Data = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        TemplateDetails: TemplateDetails,
        CreatedBy: UserId,
      };

      // console.log('API Request Data:', Data);

      const response = await dispatch(
        putPrintSelectionComponentData(Data)
      ).unwrap();

      if (response?.data?.statusCode === 1) {
        dispatch(changeSelectedPrintdummyData(false));
        await printsyleget();
        setMessageType('success');
        setMessageData(response?.data?.response);
        if (closeModel) {
          closeModel();
        }
      }
    } catch (error) {
      console.error('Error setting default template:', error);
      setMessageType('error');
      setMessageData('Failed to set default template');
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        gap: '1rem',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <div style={{ textAlign: 'center' }}>
        <p> Print : {selectedTemplate?.StyleName}</p>
      </div>
      <div style={{ display: 'flex', gap: '1rem', flexWrap:"wrap" }}>
        <div>
          {
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '1rem',
                backgroundColor: '#f5f5f5',
                padding: '0.75rem 1rem',
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                maxWidth: 'fit-content',
                margin: '1rem 0 0 0',
              }}
            >
              <span style={{ fontWeight: '500', color: '#555' }}>
                Customized
                <Tooltip title="Print will stop when the content finishes. It won't waste paper.">
                  <InfoCircleOutlined
                    style={{
                      color: '#1890ff',
                      cursor: 'pointer',
                      marginLeft: '5px',
                    }}
                  />
                </Tooltip>
              </span>

              <Switch checked={currentPrintType} onChange={onChangeToggle} />
              <span style={{ fontWeight: '500', color: '#555' }}>
                Standard
                <Tooltip title=" Print will take full paper, even if there's less content.">
                  <InfoCircleOutlined
                    style={{
                      color: '#1890ff',
                      cursor: 'pointer',
                      marginLeft: '5px',
                    }}
                  />
                </Tooltip>
              </span>
            </div>
          }
        </div>

        <div>
          {currentPrintType && (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '1rem',
                backgroundColor: '#f5f5f5',
                padding: '0.75rem 1rem',
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                maxWidth: 'fit-content',
                margin: '1rem 0 0 0',
              }}
            >
              <span style={{ fontWeight: '500', color: '#555' }}>A4</span>
              <Switch checked={currentPageSize} onChange={onChangepageSize} />
              <span style={{ fontWeight: '500', color: '#555' }}>A5</span>
            </div>
          )}
        </div>
      </div>

      <div
        style={{ display: 'flex', justifyContent: 'flex-end', width: '100%' }}
      >
        <Buttons
          buttonText="Save"
          color="901D77"
          icon={<ArrowRightOutlined />}
          htmlType={true}
          handleSubmit={onfinish}
        />
      </div>
    </div>
  );
};

export default SalesPrintSize;
