import { DeleteOutlined, DownloadOutlined, EditOutlined, FileOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons';
import { CodeListDataDto, QcClearanceDTO } from '@gtpl/shared-models/planning';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, Form, Image, Input, message, Modal, Popconfirm, Row, Select, Switch, Table, Tabs, Tag, Upload } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import { SortOrder } from 'antd/lib/table/interface';
import { UploadFile } from 'antd/lib/upload/interface';
import appSettings from 'apps/services/config';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import Highlighter from 'react-highlight-words';
import { CodeListMainService } from '../../../../../../../libs/shared-services/planning/src/lib/code-list-main-service';
import { QCClearanceInfoService } from '../../../../../../../libs/shared-services/planning/src/lib/qc-clearance.service';
import { PassOrFail } from './passOrFail-Enum';

const { TabPane } = Tabs;
const { Option } = Select;

const QCClearance = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [page, setPage] = React.useState(1);
  const [isOthersActive, setIsOthersActive] = useState(true);
  const [codeListData, setCodeListData] = useState<CodeListDataDto[]>([]);
  const [testingInfo] = Form.useForm();
  const codeListMainService = new CodeListMainService();
  const qcClearanceInfoService = new QCClearanceInfoService();
  const [fileLists, setFileLists] = useState<any[]>([]);
  const baseUrl = appSettings.planning_files_url
  const [activeTestType, setActiveTestType] = useState<'chemical' | 'micro' | 'fg' | 'others'>();
  const searchInput = useRef(null);
  const [ fileNameData, setFileNameData ] =  useState<any[]>([])
  
  useEffect(() => {
    getCodeListData();
  }, []);

  useEffect(() => {
    return () => {
      Object.values(fileLists || {}).forEach(files => {
        files.forEach(file => {
          if (file.preview) {
            URL.revokeObjectURL(file.preview);
          }
        });
      });
    };
  }, [fileLists]);
  
  const showEditModal = (record) => {
    setSelectedRecord(record);
    setIsModalVisible(true);
    setIsOthersActive(true);

    testingInfo.setFieldsValue({
      chemicalResult: record.chemResult,
      microResult: record.microResult,
      fgResult: record.fgResult,
      othersResult: record.others,
      chemicalFile: record.cFile ? [record.cFile] : [],
      microFile: record.mFile ? [record.mFile] : [],
      fgFile: record.fgFile ? [record.fgFile] : [],
      othersFile: record.othersFile ? [record.othersFile] : [],
    });
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedRecord(null);
    setActiveTestType(undefined);
    setIsOthersActive(true);
    testingInfo.resetFields();
    setFileLists([]);
    setFileNameData([]);
  };

      function handleSearch(selectedKeys: React.SetStateAction<string>[], confirm: () => void, dataIndex: React.SetStateAction<string>) {
          confirm();
          setSearchText(selectedKeys[0]);
          setSearchedColumn(dataIndex);
        };
      
        function handleReset(clearFilters: () => void) {
          clearFilters();
          setSearchText('');
          setSearchedColumn('')
        };
        

  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: any) => (
      <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value: string, record: { [x: string]: { toString: () => string; }; }) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: (visible: any) => {
      if (visible) { setTimeout(() => searchInput.current.select()); }
    },
    render: (text: { toString: () => any; }) =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : text
      ) : null
  });

  const getTagColor = (result) => {
    if (result === 'PASS') {
      return { backgroundColor: '#d9f7be', color: '#237804' };
    } else if (result === 'FAIL') {
      return { backgroundColor: '#ffccc7', color: '#a8071a' };
    } else {
      return { backgroundColor: '#f5f5f5', color: '#8c8c8c' };
    }
  };

  const showTestModal = (testType: 'chemical' | 'micro' | 'fg' | 'others', record: any) => {
    setSelectedRecord(record);
    setActiveTestType(testType);
    setIsOthersActive(true); 
    setFileLists([]); 
    setFileNameData([]); 
    testingInfo.setFieldsValue({
      [`${testType}Result`]: record[`${testType}Result`] || undefined,
      [`${testType}File`]: record[`${testType}File`] ? [record[`${testType}File`]] : []
    });

    getFileDetailsById(record.codeListMainId, testType);
    setIsModalVisible(true);
  };

  const handleTabChange = (key) => {
    setPage(1); 
  };

  const renderTestTags = (record: any) => {
    const tests = ['chemical', 'micro', 'fg', 'others'];
    return tests.map(test => {
      const result = record[`${test}Result`] || 'PENDING';
      const colorMap = {
        PASS: '#52c41a',
        FAIL: '#ff4d4f',
        PENDING: '#d9d9d9'
      };

      
      return (
        <Tag
          key={test}
          color={colorMap[result]}
          style={{ cursor: 'pointer', marginBottom: 4 }}
          onClick={() => showTestModal(test as any, record)}
        >
          {test.toUpperCase()}
        </Tag>
      );
    });
  };

  const saveInfo = async () => {
    try {
      const info = await testingInfo.validateFields();
  
      const clearanceData = {
        codeListMainId: selectedRecord.codeListMainId,
        soId: selectedRecord.saleOrderId,
        poNumber: selectedRecord.poNumber,
        soItemId: selectedRecord.saleOrderItemId,
        chemicalResult: info.chemicalResult,
        microResult: info.microResult,
        fgResult: info.fgResult,
        others: isOthersActive ? info.othersResult : "PASS",
        createdUser: localStorage.getItem("createdUser"),
        updatedUser: localStorage.getItem("createdUser"),
      };
  
      const formData = new FormData();
      const fileReferences = [];
    
      Object.entries(fileLists).forEach(([testType, files]) => {
        if (Array.isArray(files)) {
          files.forEach(file => {
            if (file?.originFileObj) {
              formData.append("filesData", file.originFileObj, file.name);
              fileReferences.push({
                reference: testType.toUpperCase(),
                fileName: file.name,
              });
            }
          });
        }
      });
  
      formData.append("clearanceData", JSON.stringify(clearanceData));
      formData.append("fileReferences", JSON.stringify(fileReferences));
  
      console.log("Sending clearanceData:", clearanceData);
      console.log("Sending fileReferences:", fileReferences);
  
      const res = await qcClearanceInfoService.createClearance(formData);
  
      if (res.status) {

        AlertMessages.getSuccessMessage(res.internalMessage);
        getCodeListData();
        handleCancel();
      } else {
        AlertMessages.getErrorMessage(res.internalMessage);
      }
    } catch (err) {
      AlertMessages.getErrorMessage(err.message);
    }
  };

  const colorMap = {
    PASS: '#52c41a',
    FAIL: '#ff4d4f',
    PENDING: '#d9d9d9'
  };
  

  const getFileDetailsById = (value, testType)=>{
    const req = new QcClearanceDTO(value,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined, testType)
    qcClearanceInfoService.getFileDetailsById(req).then(res=>{
      if(res.status){
        setFileNameData(res.data)
      }
    }).catch(error => {
      console.error('Error downloading files:', error);
      message.error('Failed to download files');
    })
  }

const handleFileChange = (testType: string, files: UploadFile[]) => {
  setFileLists(prev => ({
    ...prev,
    [testType]: files.map(file => ({
      ...file,
      preview: file.originFileObj ? URL.createObjectURL(file.originFileObj) : file.preview
    }))
  }));
};

const uploadProps = (testType: string) => ({
  fileList: fileLists[testType] || [],
  onRemove: (file: UploadFile) => {
    handleFileChange(
      testType, 
      fileLists[testType].filter(f => f.uid !== file.uid)
    );
    if (file.preview) URL.revokeObjectURL(file.preview);
    if (file.originFileObj) URL.revokeObjectURL(URL.createObjectURL(file.originFileObj));
  },
  beforeUpload: (file: File) => {
    const preview = URL.createObjectURL(file)

    handleFileChange(testType, [
      ...(fileLists[testType] || []),
      {
        uid: Date.now().toString(),
        name: file.name,
        status: 'done',
        originFileObj: file,
        preview,
        type: file.type
      }
    ]);
    return false;
  }
});
  
  const getCodeListData = async () => {
    try {
      const res = await codeListMainService.getAllCodeListsData();
      if (res.status) {
        setCodeListData(res.data);
      } else {
        AlertMessages.getErrorMessage(res.internalMessage);
        setCodeListData([]);
      }
    } catch (err) {
      AlertMessages.getErrorMessage(err.message);
      setCodeListData([]);
    }
  };

  const pendingData = codeListData?.filter((data) => data.codeListStatus === 'PENDING') || [];
  const clearedData = codeListData?.filter((data) => data.codeListStatus === 'CLEARED') || [];

  const pendingColumns: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page-1) * 10 +(index+1)
    },
    { title: 'PO Number', 
      dataIndex: 'poNumber', 
      key: 'poNumber',
          ...getColumnSearchProps("poNumber"),
        render: (value, record) => (record.poNumber ? record.poNumber : "-"),
        sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
        sortDirections: ["descend", "ascend"] as SortOrder[], },
    // { title: 'Product', 
    //   dataIndex: 'product', 
    //   key: 'product' ,
    //   ...getColumnSearchProps("product"),
    //   render: (value, record) => (record.product ? record.product : "-"),
    //   sorter: (a, b) => a.product?.localeCompare(b.product),
    //   sortDirections: ["descend", "ascend"] as SortOrder[],
    // },
    // { title: 'Trace Code',
    //    dataIndex: 'traceCode',
    //     key: 'traceCode',
    //     ...getColumnSearchProps("traceCode"),
    //     render: (value, record) => (record.traceCode ? record.traceCode : "-"),
    //     sorter: (a, b) => a.traceCode?.localeCompare(b.traceCode),
    //     sortDirections: ["descend", "ascend"] as SortOrder[],
    //   },
    // { title: 'Production Date',
    //    dataIndex: 'productionDate',
    //     key: 'productionDate', 
    //     render: (date) => date ? moment(date).format('DD/MM/YYYY') : 'N/A' ,
    //     sorter: (a, b) => a.productionDate?.localeCompare(b.productionDate),
    //     sortDirections: ["descend", "ascend"] as SortOrder[],
    //   },
    // { title: 'Expiry Date', 
    //   dataIndex: 'bestBeforeDate',
    //    key: 'bestBeforeDate', render: (date) => date ? moment(date).format('DD/MM/YYYY') : 'N/A' ,
    //    sorter: (a, b) => a.bestBeforeDate?.localeCompare(b.bestBeforeDate),
    //    sortDirections: ["descend", "ascend"] as SortOrder[],
    //   },
      {
        title: 'Tests',
        key: 'tests',
        render: (_, record) => renderTestTags(record),
      },
    // {
    //   title: "Action",
    //   key: "action",
    //   responsive: ["md"],
    //   align: "left",
    //   render: (text, record) => (
    //     <Button type="link" icon={<EditOutlined />} onClick={() => showEditModal(record)} />
    //   ),
    // },
  ];

  const testTypeLabels = {
    chemical: 'Chemical',
    micro: 'Microbiological',
    fg: 'Finished Goods',
    others: 'Others'
  };

  const handleDownload = (fileId, fileType) => {
    setFileNameData([]);
    
    const req = new QcClearanceDTO(fileId, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, fileType);

    qcClearanceInfoService.getFileDetailsById(req).then(res => {
      if (res.status && res.data.length > 0) {
        res.data.forEach((file, index) => {
          setTimeout(() => {
            const fileURL = `${baseUrl}/qcClearance/${file.fileName}`;

            fetch(fileURL).then(response => {
              if (!response.ok) throw new Error(`File not found: ${file.fileName}`);
              return response.blob();
            }).then(blob => {
              const url = window.URL.createObjectURL(blob);
              const link = document.createElement('a');
              link.href = url;
              link.download = file.fileName;
              link.onclick = () => setTimeout(() => {
                window.URL.revokeObjectURL(url);
                document.body.removeChild(link);
              }, 100);
                document.body.appendChild(link);
                link.click();
              }).catch(error => {
                console.error(`Error downloading ${file.fileName}:`, error);
                message.error(`Failed to download ${file.fileName}`);
              });
            }, index * 1000);
          });
        } else {
          message.error("No files available for download");
        }
      }).catch(error => {
        console.error("Error fetching file details:", error);
        message.error(error.response?.status === 404 ? "No files found" : "Fetch error");
      });
  };
  

  
  const clearedColumns: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page-1) * 10 +(index+1)
    },
    { title: 'PO Number',
       dataIndex: 'poNumber',
        key: 'poNumber' ,
        ...getColumnSearchProps("poNumber"),
        render: (value, record) => (record.poNumber ? record.poNumber : "-"),
        sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
        sortDirections: ["descend", "ascend"] as SortOrder[],
      },
    // { title: 'Product',
    //    dataIndex: 'product', 
    //    key: 'product' ,
    //    ...getColumnSearchProps("product"),
    //    render: (value, record) => (record.product ? record.product : "-"),
    //    sorter: (a, b) => a.product?.localeCompare(b.product),
    //    sortDirections: ["descend", "ascend"] as SortOrder[],
    //   },
    //   { title: 'Trace Code',
    //     dataIndex: 'traceCode',
    //      key: 'traceCode',
    //      ...getColumnSearchProps("traceCode"),
    //      render: (value, record) => (record.traceCode ? record.traceCode : "-"),
    //      sorter: (a, b) => a.traceCode?.localeCompare(b.traceCode),
    //      sortDirections: ["descend", "ascend"] as SortOrder[],
    //    },
    // { 
    //   title: 'Production Date', 
    //   dataIndex: 'productionDate', 
    //   key: 'productionDate', 
    //   render: (date) => date ? moment(date).format('DD/MM/YYYY') : 'N/A' ,
    //   sorter: (a, b) => a.productionDate?.localeCompare(b.productionDate),
    //   sortDirections: ["descend", "ascend"] as SortOrder[],
    // },
    // { 
    //   title: 'Expiry Date', 
    //   dataIndex: 'bestBeforeDate', 
    //   key: 'bestBeforeDate', 
    //   render: (date) => date ? moment(date).format('DD/MM/YYYY') : 'N/A' ,
    //   sorter: (a, b) => a.bestBeforeDate?.localeCompare(b.bestBeforeDate),
    //   sortDirections: ["descend", "ascend"] as SortOrder[],
    // },
    {
      title: 'Chem Result',
      dataIndex: 'chemicalResult',
      key: 'chemicalResult',
       filters: [
                    { text: 'PASS', value: PassOrFail.PASS },
                    { text: 'FAIL', value: PassOrFail.FAIL },
                  ],
                  onFilter: (value, record) => record.chemicalResult === value,
      render: (text, record) => {
        return (
          <>
            <Tag color={text === 'PASS' ? 'green' : 'red'}>{text}</Tag>
            {/* <span style={{ color: text === 'PASS' ? 'green' : 'red' }}>
          {text}
        </span> */}
              <Button
                type="link"
                style={{ marginLeft: '10px' }}
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(record.codeListMainId, 'chemical')}
              />
          </>
        );
      },
    },
    {
      title: 'Micro Result',
      dataIndex: 'microResult',
      key: 'microResult',
      filters: [
        { text: 'PASS', value: PassOrFail.PASS },
        { text: 'FAIL', value: PassOrFail.FAIL },
      ],
      onFilter: (value, record) => record.microResult === value,
      render: (text, record) => {
        return (
          <>
            <Tag color={text === 'PASS' ? 'green' : 'red'}>{text}</Tag>
              <Button
                type="link"
                style={{ marginLeft: '10px' }}
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(record.codeListMainId, 'micro')}
              />
          </>
        );
      },
    },
    {
      title: 'FG Result',
      dataIndex: 'fgResult',
      key: 'fgResult',
      filters: [
        { text: 'PASS', value: PassOrFail.PASS },
        { text: 'FAIL', value: PassOrFail.FAIL },
      ],
      onFilter: (value, record) => record.fgResult === value,
      render: (text, record) => {
        return (
          <>
            <Tag color={text === 'PASS' ? 'green' : 'red'}>{text}</Tag>
              <Button
                type="link"
                style={{ marginLeft: '10px' }}
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(record.codeListMainId, 'fg')}
              />
          </>
        );
      },
    },
    {
      title: 'Others',
      dataIndex: 'othersResult',
      key: 'others',
      filters: [
        { text: 'PASS', value: PassOrFail.PASS },
        { text: 'FAIL', value: PassOrFail.FAIL },
      ],
      onFilter: (value, record) => record.othersResult === value,
      render: (text, record) => {
        return (
          <>
            <Tag color={text === 'PASS' ? 'green' : 'red'}>{text}</Tag>
              <Button
                type="link"
                style={{ marginLeft: '10px' }}
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(record.codeListMainId, 'others')}
              />
          </>
        );
      },
    },
    {
      title: 'Result',
      dataIndex: 'overallResult',
      key: 'overallResult',
      filters: [
        { text: 'PASS', value: PassOrFail.PASS },
        { text: 'FAIL', value: PassOrFail.FAIL },
      ],
      onFilter: (value, record) => record.overallResult === value,
      render: (text) => (
        
        <span
          style={{
            backgroundColor: colorMap[text] || '#d9d9d9',
            color: '#fff',
            padding: '4px 8px',
            borderRadius: '4px',
          }}
        >
          {text}
        </span>
      ),
    }
    
  ];


  const FilePreview = ({ files, onDelete }) => {
    const imageFiles = files.filter(file => file.type?.startsWith("image/"));
    const nonImageFiles = files.filter(file => !file.type?.startsWith("image/"));
  
    return (
      <>
        {imageFiles.length > 0 && (
          <Image.PreviewGroup>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {imageFiles.map(file => (
                <div key={file.uid} style={{ position: "relative" }}>
                  <Image
                    src={file.preview}
                    width={50}
                    height={50}
                    style={{ objectFit: "cover", borderRadius: 4, cursor: "pointer" }}
                    preview={{ src: file.preview }}
                  />
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    size="small"
                    style={{
                      position: "absolute",
                      top: -5,
                      right: -5,
                      background: "white",
                      borderRadius: "50%",
                      boxShadow: "0 0 5px rgba(0,0,0,0.2)"
                    }}
                    onClick={() => onDelete(file)}
                  />
                </div>
              ))}
            </div>
          </Image.PreviewGroup>
        )}
  
        {nonImageFiles.length > 0 &&
          nonImageFiles.map(file => (
            <div key={file.uid} style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
              <FileOutlined style={{ fontSize: 24 }} />
              <div style={{ flex: 1 }}>
                <div>{file.name}</div>
                <div style={{ fontSize: 12, color: "#666" }}>
                  {file.size && `${(file.size / 1024).toFixed(1)}KB `}
                  {file.name.split(".").pop().toUpperCase()}
                </div>
              </div>
  
              <Button
                type="link"
                icon={<DownloadOutlined />}
                onClick={() => {
                  const link = document.createElement("a");
                  link.href = file.preview;
                  link.download = file.name;
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
                }}
              />
  
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                onClick={() => onDelete(file)}
              />
            </div>
          ))}
      </>
    );
  };
  

  return (
    <Card
      size="small"
      title={<span style={{ color: 'white' }}>QC Clearance</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <Tabs centered onChange={handleTabChange}>
        <TabPane tab="Pending" key="1">
          <Table 
          columns={pendingColumns} 
          dataSource={pendingData} 
          pagination={{
            onChange(current) {
              setPage(current);
            }
          }}
          />
        </TabPane>
        <TabPane tab="Cleared" key="2">
          <Table 
          columns={clearedColumns} 
          dataSource={clearedData} 
          pagination={{
            onChange(current) {
              setPage(current);
            }
          }}
          />
        </TabPane>
      </Tabs>
  
      <Modal
        title={`${testTypeLabels[activeTestType]} Test Results`}
        visible={isModalVisible}
        onOk={saveInfo}
        onCancel={handleCancel}
        width={600}
        bodyStyle={{ padding: '24px 32px' }}
        footer={
          selectedRecord?.[`${activeTestType}Result`] === "PASS" || 
          selectedRecord?.[`${activeTestType}Result`] === "FAIL" 
            ? null 
            : [
                <Button key="cancel" onClick={handleCancel}>Cancel</Button>,
                <Button key="submit" type="primary" onClick={saveInfo}>OK</Button>
              ]
        }
      >
        <Form form={testingInfo} layout="vertical">
          {activeTestType && (
            <>
              {activeTestType === 'others' && (
                <Row justify="end">
                  <Col>
                    <Form.Item
                      label="Is this Required ?"
                      valuePropName="checked"
                      initialValue={true}
                      style={{ 
                        marginBottom: 0, 
                        display: 'flex', 
                        alignItems: 'center' 
                      }}
                      labelCol={{ style: { marginRight: 8, flex: 'none' } }} 
                      wrapperCol={{ style: { flex: 'none' } }} 
                    >
                      <Switch
                        checked={isOthersActive}
                        onChange={(checked) => {
                          setIsOthersActive(checked);
                          if (!checked) {
                            testingInfo.setFieldsValue({ othersResult: 'PASS' });
                          } else {
                            testingInfo.setFieldsValue({ othersResult: undefined });
                          }
                        }}
                      />
                    </Form.Item>
                  </Col>
                </Row>
              )}
  
              <Form.Item
                name={`${activeTestType}Result`}
                label="Test Result"
                rules={[
                  { 
                    required: activeTestType !== 'others' || isOthersActive, 
                    message: 'Please select a result' 
                  }
                ]}
              >
                <Select 
                  placeholder="Select Result" 
                  disabled={
                    selectedRecord?.[`${activeTestType}Result`] === "PASS" || 
                    selectedRecord?.[`${activeTestType}Result`] === "FAIL" ||
                    (activeTestType === 'others' && !isOthersActive)
                  }
                >
                  <Option value="PASS">PASS</Option>
                  <Option value="FAIL">FAIL</Option>
                </Select>
              </Form.Item>
  
              {!(selectedRecord?.[`${activeTestType}Result`] === "PASS" || 
                 selectedRecord?.[`${activeTestType}Result`] === "FAIL") && (
                <Form.Item
                  name={`${activeTestType}File`}
                  label="Upload Documents"
                  extra="Supports images, PDFs, and documents"
                >
                  <Upload
                    showUploadList={false}
                    {...uploadProps(activeTestType)}
                    disabled={activeTestType === 'others' && !isOthersActive}
                  >
                    <Button
                      icon={<UploadOutlined />}
                      disabled={activeTestType === 'others' && !isOthersActive}
                    >
                      Click to Upload
                    </Button>
                  </Upload>
                </Form.Item>
              )}
  
              <div style={{ marginTop: 16 }}>
                <FilePreview 
                  files={fileLists[activeTestType] || []} 
                  onDelete={(file) => {
                    setFileLists(prev => ({
                      ...prev,
                      [activeTestType]: prev[activeTestType]?.filter(f => f.uid !== file.uid) || []
                    }));
                    URL.revokeObjectURL(file.preview);
                  }}
                />
              </div>
  
              <div>
                {fileNameData.length > 0 && (
                  <div style={{ marginTop: 16 }}>
                    <Image.PreviewGroup>
                      {fileNameData.map((file) => {
                        const isImage = file.fileName.match(/\.(jpeg|jpg|png|gif|webp)$/i);
                        const fileUrl = `${baseUrl}/qcClearance/${file.fileName}`;
  
                        return (
                          <div key={file.fileName} style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                            {isImage ? (
                              <Image width={50} height={50} src={fileUrl} />
                            ) : (
                              <FileOutlined style={{ fontSize: 24 }} />
                            )}
                            <a href={fileUrl} download>{file.fileName}</a>
                            <Button type="link" icon={<DownloadOutlined />} onClick={() => window.open(fileUrl, "_blank")} />
                          </div>
                        );
                      })}
                    </Image.PreviewGroup>
                  </div>
                )}
              </div>
            </>
          )}
        </Form>
      </Modal>
    </Card>
  );
};

export default QCClearance;