/* eslint-disable spellcheck/spell-checker */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useRef } from 'react';
import { Collapse, Typography, Row, Col, Form, Spin, FormInstance, Checkbox } from 'antd';
import { LEADS_STATUS, ALL_TAB_OPTIONS, TAB_LABEL_MAP } from '@/utills/constant';
import InputSelect from '@/components/form/InputSelect';
import { useRoles } from '@/hooks/useRoles';

const { Panel } = Collapse;

interface TransferValidationItem {
  launch_id: number;
  launch_name: string;
  show_for_pair_resolve: boolean;
  show_for_self_transfer: boolean;
}

interface IEmployeeLaunchTransferProps {
  transferValidationData: TransferValidationItem[];
  launchPreviewCounts: Record<number, any>;
  previewLoading: Record<number, boolean>;
  filterLaunchLList: any[];
  form: FormInstance;
  fetchPreviewCounts: (launchId: number, tabStatuses: string[], currentStatuses?: number[]) => Promise<void>;
  invalidLaunchIds?: number[];
  roleId?: string | number;
}

const EmployeeLaunchTransfer: React.FC<IEmployeeLaunchTransferProps> = ({
  transferValidationData,
  launchPreviewCounts,
  previewLoading,
  filterLaunchLList,
  form,
  fetchPreviewCounts,
  invalidLaunchIds = [],
  roleId,
}) => {
  const { getRoleByName } = useRoles();
  const isPreSales = Number(roleId) === getRoleByName('pre_sales')?.id;
  // Pre Sales: visited tab is excluded (visited leads stay in old launch, same as booking done for FS)
  const availableTabOptions = isPreSales
    ? ALL_TAB_OPTIONS.filter((t) => t !== 'visited')
    : ALL_TAB_OPTIONS;
  const launchesWithLeads = transferValidationData.filter((l) => l.show_for_self_transfer);
  const transfersWatch = Form.useWatch('transfers', form);
  const fetchPreviewRef = useRef(fetchPreviewCounts);
  fetchPreviewRef.current = fetchPreviewCounts;
  const prevTabStatusRef = useRef<Record<string, string>>({});
  const prevStatusIdsRef = useRef<Record<string, string>>({});

  useEffect(() => {
    if (!transfersWatch) return;
    launchesWithLeads.forEach((launchData) => {
      const lid = String(launchData.launch_id);
      const t = transfersWatch[lid];

      const tabStatuses: string[] = Array.isArray(t?.tab_status) ? t.tab_status : [];
      const statusIds: number[] = Array.isArray(t?.current_status)
        ? t.current_status.map(Number).filter((n: number) => !isNaN(n))
        : [];

      const tabKey = tabStatuses.join(',');
      const statusKey = statusIds.join(',');

      if (tabKey === prevTabStatusRef.current[lid] && statusKey === prevStatusIdsRef.current[lid]) return;

      prevTabStatusRef.current[lid] = tabKey;
      prevStatusIdsRef.current[lid] = statusKey;

      fetchPreviewRef.current(launchData.launch_id, tabStatuses, statusIds);
    });
  }, [transfersWatch]);

  if (launchesWithLeads.length === 0) return null;

  const allLeadStatusOptions = Object.values(LEADS_STATUS).map((s: any) => ({
    label: s.name,
    value: s.id,
  }));

  return (
    <>
      <div style={{ marginBottom: 12, padding: '8px 12px', background: '#e6f0ff', borderRadius: 4, borderLeft: '3px solid #1677ff' }}>
        <Typography.Text style={{ color: '#1F4D74', fontSize: 16 }}>
          To transfer any lead under any other team mate of the sales person please visit{' '}
          <Typography.Link
            href="/lead-transfer"
            target="_blank"
            style={{ textDecoration: 'underline', fontWeight: 600, color: '#1677ff' }}
          >
            here
          </Typography.Link>.
        </Typography.Text>
      </div>

      {/* When there are invalid launches, expand all of them so inline errors are visible. */}
      <Collapse
        ghost
        expandIconPosition="end"
        style={{ background: 'transparent' }}
        key={invalidLaunchIds.length > 0 ? `err-${invalidLaunchIds.join(',')}` : 'default'}
        defaultActiveKey={
          invalidLaunchIds.length > 0
            ? launchesWithLeads.map(l => `launch_${l.launch_id}`)
            : launchesWithLeads.length > 0 ? [`launch_${launchesWithLeads[0].launch_id}`] : []
        }
      >
        {launchesWithLeads.map((launchData) => {
          const lid = launchData.launch_id;
          const preview = launchPreviewCounts[lid];
          const isPreviewLoading = previewLoading[lid];
          const currentTabStatuses: string[] = transfersWatch?.[String(lid)]?.tab_status || [];
          const t = transfersWatch?.[String(lid)];
          const isMissingLaunch = invalidLaunchIds.includes(lid) && !t?.new_launch_id;
          const isMissingTab = invalidLaunchIds.includes(lid) && (!t?.tab_status || t.tab_status.length === 0);
          const isInvalid = isMissingLaunch || isMissingTab;

          return (
            <Panel
              header={<Typography.Text strong>{launchData.launch_name}</Typography.Text>}
              key={`launch_${lid}`}
              style={isInvalid ? { border: '1px solid #ff4d4f', borderRadius: 6 } : undefined}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item label="Previous Launch">
                    <InputSelect
                      name={['transfers', String(lid), 'old_launch_id']}
                      disabled
                      placeholder={launchData.launch_name}
                      options={[{ label: launchData.launch_name, value: lid }]}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <InputSelect
                    name={['transfers', String(lid), 'new_launch_id']}
                    label="Transfer To Launch"
                    status={isMissingLaunch ? 'error' : undefined}
                    rules={[{ required: true, message: '' }]}
                    options={filterLaunchLList
                      ?.filter((item: any) => Number(item.launch_id) !== Number(lid))
                      .map((item: any) => ({
                        label: item.launch_name,
                        value: item.launch_id,
                      }))}
                  />
                  {isMissingLaunch && (
                    <Typography.Text type="danger" strong style={{ fontSize: 12, display: 'block', marginTop: -16, marginBottom: 8 }}>
                      Please select a target launch
                    </Typography.Text>
                  )}
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={12}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
                    <Typography.Text style={{ fontSize: 13 }}>
                      Tab Status <span style={{ color: 'red' }}>*</span>
                    </Typography.Text>
                    <Typography.Link
                      style={{ fontSize: 12 }}
                      onClick={() => {
                        form.setFieldValue(['transfers', String(lid), 'tab_status'], availableTabOptions);
                        form.validateFields([['transfers', String(lid), 'tab_status']]);
                      }}
                    >
                      Select All
                    </Typography.Link>
                  </div>
                  <InputSelect
                    name={['transfers', String(lid), 'tab_status']}
                    label={undefined}
                    mode="multiple"
                    status={isMissingTab ? 'error' : undefined}
                    rules={[{ required: true, message: '' }]}
                    options={availableTabOptions.map((v) => ({ label: TAB_LABEL_MAP[v], value: v }))}
                  />
                  {isMissingTab && (
                    <Typography.Text type="danger" strong style={{ fontSize: 12, display: 'block', marginTop: 2 }}>
                      Please select at least one tab status
                    </Typography.Text>
                  )}
                </Col>
                <Col span={12}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
                    <Typography.Text style={{ fontSize: 13 }}>Current Status</Typography.Text>
                    <Typography.Link
                      style={{ fontSize: 12 }}
                      onClick={() => {
                        const allIds = allLeadStatusOptions.map((o: any) => Number(o.value)).filter((n: number) => !isNaN(n));
                        form.setFieldValue(['transfers', String(lid), 'current_status'], allIds);
                      }}
                    >
                      Select All
                    </Typography.Link>
                  </div>
                  <InputSelect
                    name={['transfers', String(lid), 'current_status']}
                    label={undefined}
                    mode="multiple"
                    options={allLeadStatusOptions}
                  />
                </Col>
              </Row>

              {currentTabStatuses.length > 0 && (
                <div style={{ marginTop: 8, marginBottom: 8, padding: '12px', background: '#fafafa', borderRadius: 4, border: '1px solid #f0f0f0' }}>
                  {isPreviewLoading ? (
                    <Spin size="small" />
                  ) : preview ? (
                    <div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 16px', marginBottom: preview.transferring_leads !== undefined ? 12 : 0 }}>
                        {currentTabStatuses.map((tab: string) => {
                          const excluded = preview.excluded_counts?.[tab] ?? 0;
                          return (
                            <span key={tab}>
                              <Typography.Text strong>{TAB_LABEL_MAP[tab] || tab}</Typography.Text>:
                              {' '}<Typography.Text>{preview.tab_counts?.[tab] ?? 0} leads</Typography.Text>
                              {excluded > 0 && (
                                <Typography.Text type="secondary" style={{ fontSize: 11 }}> ({excluded} won&apos;t transfer)</Typography.Text>
                              )}
                            </span>
                          );
                        })}
                      </div>

                      {(preview.transferring_leads !== undefined || preview.dieing_leads !== undefined) && (
                        <div style={{ paddingTop: 12, borderTop: '1px dashed #d9d9d9' }}>
                          <div style={{ marginBottom: 4 }}>
                            <Typography.Text>Leads to be <Typography.Text strong style={{ color: '#1677ff' }}>transferred</Typography.Text>: </Typography.Text>
                            <Typography.Text strong>{preview.transferring_leads ?? 0}</Typography.Text>
                          </div>
                          <div>
                            <Typography.Text>Remaining leads to be marked as <Typography.Text strong style={{ color: '#ff4d4f' }}>Dead</Typography.Text>: </Typography.Text>
                            <Typography.Text strong>{preview.dieing_leads ?? 0}</Typography.Text>
                          </div>
                          {preview.excluded_counts?._total_unique > 0 && (
                            <div style={{ marginTop: 2 }}>
                              <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                                Of the leads above, {preview.excluded_counts._total_unique} won&apos;t transfer (protected status: Booking Done{isPreSales ? ' / Visit Done' : ''}).
                              </Typography.Text>
                            </div>
                          )}
                          {preview.dieing_leads > 0 && (
                            <>
                              <div style={{ marginTop: 8, padding: '4px 8px', background: '#fffbe6', border: '1px solid #ffe58f', borderRadius: 4 }}>
                                <Typography.Text type="warning" style={{ fontSize: 12 }}>&#9888; The dead lead count can contain (visited/booked/token done) leads count also.</Typography.Text>
                              </div>
                              <Form.Item
                                name={['transfers', String(lid), 'mark_remaining_dead']}
                                valuePropName="checked"
                                initialValue={false}
                                rules={[{
                                  validator: (_, value) =>
                                    value ? Promise.resolve() : Promise.reject(new Error('You must confirm marking remaining leads as Dead to proceed.')),
                                }]}
                                style={{ marginTop: 10, marginBottom: 0 }}
                              >
                                <Checkbox>
                                  <Typography.Text strong type="danger">
                                    I confirm that the remaining {preview.dieing_leads} lead(s) should be marked as Dead and reassigned to the Team Lead.
                                  </Typography.Text>
                                </Checkbox>
                              </Form.Item>
                            </>
                          )}
                        </div>
                      )}
                    </div>
                  ) : null}
                </div>
              )}
            </Panel>
          );
        })}
      </Collapse>
    </>
  );
};

export default EmployeeLaunchTransfer;
