/* eslint-disable spellcheck/spell-checker */
import React, { useRef, useState } from 'react';
import { Modal, Form, Spin, notification, Table, Alert, Button } from 'antd';
import type { ModalBoxProps } from '../interface';
import { checkDuplicateLead, importLeads, reviveLead, reviveAllLeads } from '../service';
import MasterCreateLeadRequestLaunchs from '@/components/masterDropdowns/MasterCreateLeadRequestLaunchs';
import { useSearchParams } from 'next/navigation';
import MasterLaunchProjects, { MasterLaunchProjectsProps } from '@/components/masterDropdowns/MasterLaunchProjects';
import DuplicateLeadModal from './DuplicateLeadModal';
import { DuplicateCheckResponse } from '../interface';
import { EyeOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd/lib';

const LeadImportModalBox: React.FC<ModalBoxProps> = ({ isModalOpen, handleClose }) => {
  const [form] = Form.useForm();
  const queryParams = useSearchParams();
  const launchProjects = useRef<MasterLaunchProjectsProps>(null);
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState<File | null | string>(null);
  const [failedRows, setFailedRows] = useState<Array<{ row: string, field: string, message: string }>>([]);
  const [duplicateRows, setDuplicateRows] = useState<Array<{ row: number, whatsapp_number: string, customer_name: string, lead_id: number, status_name: string, existing_customer_name: string, project_name: string, launch_id: number, pre_sales_id?: number | null, field_sales_id?: number | null }>>([]);
  const [isDuplicateModalOpen, setIsDuplicateModalOpen] = useState(false);
  const [duplicateResponse, setDuplicateResponse] = useState<DuplicateCheckResponse | null>(null);
  const [reviving, setReviving] = useState(false);
  const [revivingAll, setRevivingAll] = useState(false);
  const [selectedLaunchName, setSelectedLaunchName] = useState<string>('');
  const [selectedProjectName, setSelectedProjectName] = useState<string>('');
  const [inFileDuplicates, setInFileDuplicates] = useState<Array<{ whatsapp_number: string; original_number: string; rows: number[]; message: string }>>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const onFinish = async () => {
    if (!file || file == null) {
      notification.error({
        message: 'Error',
        description: 'Please select a valid Excel file with .xlsx or .xls extension',
      });
      return;
    }
    setLoading(true);
    try {
      const launch_id = form.getFieldValue('launch_id');
      const project_id = form.getFieldValue('project_id');
      const formData = new FormData();
      formData.append('file', file);
      formData.append('launch_id', launch_id);
      formData.append('project_id', project_id);

      const response = await importLeads(formData);
      if (response?.success && response?.successRow?.length > 0) {
        notification.success({
          message: 'Success',
          description: response?.message,
        });
      }
      if (response?.failedRow && Object.keys(response?.failedRow)?.length > 0) {
        const failedRow = response?.failedRow as Record<string, Record<string, string>>;
        const formattedFailedRows: React.SetStateAction<{ row: string; field: string; message: string; }[]> = [];

        Object.entries(failedRow).forEach(([row, errors]) => {
          Object.entries(errors).forEach(([field, message]) => {
            let errorMessage = message;
            // Check for specific errors and customize error message
            if (field === 'Configuration') {
              errorMessage = `Configuration error: ${message}`;
            } else if (field === 'FieldSales and Presales') {
              errorMessage = `FieldSales and Presales error: ${message}`;
            }
            formattedFailedRows.push({ row, field, message: errorMessage });
          });
        });

        setFailedRows(formattedFailedRows);
      } else {
        setFailedRows([]);
      }

      // Handle duplicate rows
      if (response?.duplicateRows && response.duplicateRows.length > 0) {
        setDuplicateRows(response.duplicateRows);
      } else {
        setDuplicateRows([]);
      }

      // Only reset the file field — retain launch and project selections
      form.setFieldsValue({ file: undefined });
      setFile(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } catch (error: any) {
      const responseData = error?.response?.data;
      if (responseData?.inFileDuplicates && responseData.inFileDuplicates.length > 0) {
        setInFileDuplicates(responseData.inFileDuplicates);
        setFile(null);
        if (fileInputRef.current) fileInputRef.current.value = '';
        form.setFieldsValue({ file: undefined });
      } else {
        const message = responseData?.message || 'An error occurred while importing leads';
        notification.error({
          message: 'Error',
          description: message,
        });
      }
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (e: any) => {
    setInFileDuplicates([]);
    const selectedFile = e.target.files[0];
    const allowedExtensions = ['.xlsx', '.xls'];
    const fileExtension = selectedFile.name.slice(selectedFile.name.lastIndexOf('.'));
    if (!allowedExtensions.includes(fileExtension)) {
      notification.error({
        message: 'Error',
        description: 'Please select a valid Excel file with .xlsx or .xls extension',
      });

      return;
    } else {
      setFile(selectedFile);
    }
  };

  const copyAllErrors = () => {
    const allErrors = failedRows?.map(row => `Row: ${row?.row}, ${row?.field}: ${row?.message}`)?.join('\n');
    navigator?.clipboard.writeText(allErrors);
    notification.success({
      message: 'Copied!',
      description: 'All errors copied to clipboard',
    });
  };
  const handleCheckDuplicate = async (whatsapp_number: string, launch_id: number, assigned_user_id: number) => {
    setLoading(true);
    try {
      const res = await checkDuplicateLead(whatsapp_number, launch_id, assigned_user_id);
      if (res?.isDuplicate) {
        setDuplicateResponse(res);
        setIsDuplicateModalOpen(true);
      } else {
        notification.info({
          message: 'Check Duplicate',
          description: 'No active or dead duplicate leads found for this launch. This lead should be safe to import.',
        });
      }
    } catch (error: any) {
      notification.error({
        message: 'Error',
        description: error?.response?.data?.message || 'Failed to check duplicate lead',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleRevive = async (leadId: number) => {
    const pre_sales_id = duplicateRows[0]?.pre_sales_id;
    const field_sales_id = duplicateRows[0]?.field_sales_id;
    setReviving(true);
    try {
      const selectedLaunchId = form.getFieldValue('launch_id');
      const selectedProjectId = form.getFieldValue('project_id');
      const reviveDate = new Date().toLocaleDateString('en-IN', { day: '2-digit', month: '2-digit', year: 'numeric' });
      const autoRemark = `Lead revived via import on ${reviveDate} in ${selectedLaunchName} and project ${selectedProjectName}`;
      const res = await reviveLead(leadId, selectedLaunchId, selectedProjectId, 'importing', autoRemark, pre_sales_id, field_sales_id);
      notification.success({
        message: 'Success',
        description: res.message || 'Lead revived successfully',
      });
      setIsDuplicateModalOpen(false);
      // Removed the revived lead from table list
      setDuplicateRows(prev => prev.filter(row => row.lead_id !== leadId));
    } catch (error: any) {
      notification.error({
        message: 'Error',
        description: error?.response?.data?.message || 'Failed to revive lead',
      });
    } finally {
      setReviving(false);
    }
  };

  const handleReviveAll = async () => {
    const revivableLeads = duplicateRows.filter(row => (row as any).canRevive);
    if (revivableLeads.length === 0) return;

    setRevivingAll(true);
    try {
      const selectedLaunchId = form.getFieldValue('launch_id');
      const selectedProjectId = form.getFieldValue('project_id');
      const reviveDate = new Date().toLocaleDateString('en-IN', { day: '2-digit', month: '2-digit', year: 'numeric' });
      const autoRemark = `Multiple leads revived via import on ${reviveDate} in ${selectedLaunchName} and project ${selectedProjectName}`;

      const leads = revivableLeads.map(row => ({
        id: row.lead_id,
        pre_sales_id: (row as any).pre_sales_id,
        field_sales_id: (row as any).field_sales_id
      }));

      const res = await reviveAllLeads(leads, selectedLaunchId, selectedProjectId, autoRemark);

      notification.success({
        message: 'Success',
        description: res.message || `${res.revivedCount} leads revived successfully`,
      });

      // Filter out successfully revived leads
      const revivedIdSet = new Set(res.revivedIds);
      setDuplicateRows(prev => prev.filter(row => !revivedIdSet.has(row.lead_id)));
    } catch (error: any) {
      notification.error({
        message: 'Error',
        description: error?.response?.data?.message || 'Failed to revive leads',
      });
    } finally {
      setRevivingAll(false);
    }
  };

  const duplicateColumns = [
    {
      title: 'Row',
      dataIndex: 'row',
      key: 'row',
      width: 60,
    },
    {
      title: 'WhatsApp Number',
      dataIndex: 'whatsapp_number',
      key: 'whatsapp_number',
      width: 140,
    },
    {
      title: 'Customer Name',
      dataIndex: 'customer_name',
      key: 'customer_name',
      width: 150,
    },
    // {
    //   title: 'Current Status',
    //   dataIndex: 'status_name',
    //   key: 'status_name',
    //   width: 150,
    //   render: (text: string, record: any) => (
    //     <span
    //       onClick={() => {
    //         window.open(`/enquiries?id=${record.lead_id}`, '_blank');
    //       }}
    //       style={{ color: '#1677ff', fontWeight: 600, textDecoration: 'underline', cursor: 'pointer' }}
    //     >
    //       {text}
    //     </span>
    //   ),
    // },
    {
      title: 'Project',
      dataIndex: 'project_name',
      key: 'project_name',
      width: 150,
    },
    {
      title: 'Action',
      key: 'action',
      align: 'center' as const,
      width: 100,
      render: (_: any, record: any) => {
        const isRevivable = record.canRevive;

        return (
          <Tooltip title={isRevivable ? 'Revive' : 'Not Revivable'}>
            <Button
              type="primary"
              shape="circle"
              icon={<EyeOutlined />}
              size="middle"
              style={
                !isRevivable
                  ? {
                    backgroundColor: '#ff4d4f',
                    borderColor: '#ff4d4f',
                  }
                  : {}
              }
              onClick={() => handleCheckDuplicate(record.whatsapp_number, record.launch_id, record.pre_sales_id ? record.pre_sales_id : record.field_sales_id)}
            />
          </Tooltip>
        );
      },
    },
  ];

  const columns = [
    {
      title: 'Row',
      dataIndex: 'row',
      key: 'row',
      width: 100,
    },
    {
      title: 'Field',
      dataIndex: 'field',
      key: 'field',
      width: 150,
    },
    {
      title: 'Message',
      dataIndex: 'message',
      key: 'message',
      width: 400,
    },
  ];

  return (
    <Modal
      title={'Import File'}
      visible={isModalOpen}
      maskClosable={duplicateRows.length > 0 ? false : true}
      keyboard={duplicateRows.length > 0 ? false : true}
      onOk={() => form.submit()}
      okText="Upload"
      onCancel={() => {
        form.resetFields();
        setFile(null);
        setFailedRows([]);
        setDuplicateRows([]);
        setInFileDuplicates([]);
        handleClose();
      }}
      className="custom-new-modal"
      width={800}
      footer={[
        <Button key="cancel" onClick={() => {
          handleClose(); setFailedRows([]); setDuplicateRows([]); setInFileDuplicates([]);
        }}>
          Cancel
        </Button>,
        <Button key="submit" type="primary" onClick={() => form.submit()}>
          Upload
        </Button>,
      ]}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          onFinish={onFinish}
          colon={false}
          labelAlign="left"
          labelCol={{ span: 9 }}
          wrapperCol={{ span: 15 }}
        >
          <MasterCreateLeadRequestLaunchs
            exclude={queryParams.get('launch_id') as string}
            name="launch_id"
            label="Launch"
            rules={[{ required: true, message: 'Please Select Launch' }]}
            placeholder="Select launch"
            onSelect={(value) => {
              form.setFieldsValue({
                launch_id: value,
              });
              if (launchProjects.current?.reload) {
                launchProjects.current?.reload(value);
                form.setFieldsValue({
                  project_id: undefined,
                });
                setSelectedProjectName('');
              }
            }}
            onChange={(_value, item) => {
              const selected = Array.isArray(item) ? item[0] : item;
              setSelectedLaunchName(selected?.label ? String(selected.label) : '');
            }}
            onClear={() => {
              form.resetFields(['launch_id']);
              setSelectedLaunchName('');
              if (launchProjects.current?.reload) {
                launchProjects.current?.reload(undefined);
                form.setFieldsValue({
                  project_id: undefined,
                });
                setSelectedProjectName('');
              }
            }}
          />
          <MasterLaunchProjects
            ref={launchProjects}
            name="project_id"
            label="Project"
            rules={[{ required: true, message: 'Please Select Project' }]}
            placeholder="Select project"
            onSelect={(value) => {
              form.setFieldsValue({
                project_id: value,
              });
            }}
            onChange={(_value, item) => {
              const selected = Array.isArray(item) ? item[0] : item;
              setSelectedProjectName(selected?.label ? String(selected.label) : '');
            }}
            onClear={() => {
              form.setFieldsValue({
                project_id: null,
              });
              setSelectedProjectName('');
            }}
            loading={false}
            id={15}
          />
          <Form.Item
            name="file"
            label="Import File"
            rules={[{ required: true, message: 'Please Select a File' }]}
          >
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              className="import-file-input"
            />
          </Form.Item>
        </Form>
        {inFileDuplicates.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <Alert
              type="error"
              showIcon
              message={
                <span style={{ fontWeight: 600 }}>
                  {inFileDuplicates.length} duplicate WhatsApp number{inFileDuplicates.length > 1 ? 's' : ''} found within the file — please remove them and re-upload.
                </span>
              }
              style={{ marginBottom: 10 }}
            />
            <div
              style={{
                border: '1px solid #ffe58f',
                borderRadius: 6,
                background: '#fffbe6',
                padding: '10px 14px',
                maxHeight: 200,
                overflowY: 'auto',
              }}
            >
              {inFileDuplicates.map((dup, idx) => (
                <div
                  key={dup.whatsapp_number}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    padding: '5px 0',
                    borderBottom: '1px solid #ffe58f',
                  }}
                >
                  <span style={{ color: '#888', fontSize: 12, minWidth: 20, textAlign: 'right' }}>
                    {idx + 1}.
                  </span>
                  <span
                    style={{
                      fontWeight: 700,
                      fontSize: 13,
                      color: '#333',
                      minWidth: 130,
                    }}
                  >
                    {dup.original_number}
                  </span>
                  <span style={{ color: '#555', fontSize: 12 }}>
                    appears in row{dup.rows.length > 1 ? 's' : ''}{' '}
                    {dup.rows.map((r, i) => (
                      <span key={r}>
                        <span style={{ fontWeight: 600 }}>{r}</span>
                        {i < dup.rows.length - 1 ? <span style={{ margin: '0 4px', color: '#aaa' }}>&amp;</span> : null}
                      </span>
                    ))}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
        {failedRows.length > 0 && (
          <>
            <Alert
              message="There are errors in the imported file. Please review the details below."
              type="error"
              showIcon
              style={{ marginBottom: 16 }}
              action={
                <Button onClick={copyAllErrors} size="small">
                  Copy All Errors
                </Button>
              }
            />
            <Table
              dataSource={failedRows}
              columns={columns}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 700, y: 300 }}
              rowKey={(record) => `${record?.row}-${record?.field}`}
            />
          </>
        )}
        {duplicateRows.length > 0 && (
          <>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: 16,
                marginTop: failedRows.length > 0 ? 16 : 0,
              }}
            >
              <Alert
                message={`${duplicateRows.length} duplicate lead(s) found and skipped. Click on the Action to view the existing lead. Green Eye = 'Revivable' ,  Red Eye = 'Not Revivable'`}
                type="warning"
                showIcon
                style={{ flex: 1, marginRight: 12 }}
              />

              {duplicateRows.some(r => (r as any).canRevive) && (
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={revivingAll}
                  onClick={handleReviveAll}
                >
                  Revive All ({duplicateRows.filter(r => (r as any).canRevive).length})
                </Button>
              )}
            </div>

            <Table
              dataSource={duplicateRows}
              columns={duplicateColumns}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 700, y: 300 }}
              rowKey={(record) => `dup-${record?.row}-${record?.lead_id}`}
            />
          </>
        )}
        <DuplicateLeadModal
          open={isDuplicateModalOpen}
          duplicateResponse={duplicateResponse}
          onClose={() => setIsDuplicateModalOpen(false)}
          onGoToLead={(id) => {
            window.open(`/enquiries?id=${id}`, '_blank');
          }}
          onRevive={handleRevive}
          onIgnore={() => setIsDuplicateModalOpen(false)}
          reviving={reviving}
        />
      </Spin>
    </Modal>
  );
};

export default LeadImportModalBox;
