import React, { useImperativeHandle, forwardRef, useEffect, useState } from 'react';
import { ClockCircleOutlined, SwapOutlined } from '@ant-design/icons';
import { fetchLeadRemarks } from '../slice';
import { useDispatch, useSelector } from 'react-redux';
import { displayDate, displayTime } from '@/utills/helper';
import type { AppDispatch, RootState } from '@/store/store';
import type { remarkItem } from '../interface';
import { follow_up_date_show, scheduled_date_show } from '../constant';
import { Timeline, Spin, Tag, Empty } from 'antd';
import { getLeadTransferHistory } from '../service';

interface TransferHistoryItem {
  id: number;
  lead_id: number;
  from_launch_name: string;
  to_launch_name: string;
  from_employee_name: string;
  to_employee_name: string;
  transferred_by_name: string;
  transfer_type: string;
  remark: string | null;
  created_at: string;
}

interface RemarkPanelProps {
    id?: number | string
    forwardRef?: React.Ref<{ reload: () => void }>
    leadDetailById?: any
}
const RemarkPanel: React.FC<RemarkPanelProps> = forwardRef(({ id, forwardRef, leadDetailById }) => {
  const dispatch: AppDispatch = useDispatch();
  const remarkData = useSelector((state: RootState) => state?.allLeads?.leadRemarks);
  const [transferHistory, setTransferHistory] = useState<TransferHistoryItem[]>([]);
  const [transferLoading, setTransferLoading] = useState(false);

  useEffect(() => {
    fetchRemarks();
    if (leadDetailById?.is_transferred === 1 && leadDetailById?.id) {
      loadTransferHistory(leadDetailById.id);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [leadDetailById?.id]);

  const loadTransferHistory = async(leadId: number) => {
    setTransferLoading(true);
    try {
      const response = await getLeadTransferHistory(leadId);
      setTransferHistory(response?.data || []);
    } catch {
      // silent
    } finally {
      setTransferLoading(false);
    }
  };

  const fetchRemarks = () => {
    dispatch(fetchLeadRemarks(id));
  };

  useImperativeHandle(forwardRef, () => ({
    reload: async() => {
      fetchRemarks();
    },
  }));
  const isFollowUpDateVisible = follow_up_date_show.some(
    (item) => item.id === leadDetailById?.status_id
  );
  const isScheduledDateVisible = scheduled_date_show.some(
    (item) => item.id === leadDetailById?.status_id
  );

  return (
    <>
    <ul className="custom-timeline">
      <div style={{ margin: '3px 30px' }}>
        {isFollowUpDateVisible && leadDetailById?.meta_data?.follow_up_at && (
          <div style={{ color:'#47474a' }}>
            <strong>Next Action - Follow-up Date:</strong>{' '}
            {displayDate(leadDetailById?.meta_data?.follow_up_at)}{' '}
            {displayTime(leadDetailById?.meta_data?.follow_up_at)}
          </div>
        )}
        {isScheduledDateVisible && leadDetailById?.meta_data?.scheduled_at && (
          <div>
            <strong>Next Action - Scheduled Date:</strong>{' '}
            {displayDate(leadDetailById?.meta_data?.scheduled_at)}{' '}
            {displayTime(leadDetailById?.meta_data?.scheduled_at)}
          </div>
        )}
      </div>

      {remarkData?.map((item: remarkItem) => {
        // Only show project name if "Site Visit Done" is included in the item's title
        const dynamicProjectName =  item?.title || '';
        return (
          <li className="custom-timeline-item" key={`${item.id}-remarks`}>
            <div className="custom-timeline-item-tail">
              <ClockCircleOutlined />
            </div>
            <div className="custom-timeline-item-content">
              <h4 dangerouslySetInnerHTML={{ __html: dynamicProjectName }} />
              <p>{item.remark}</p>
            </div>
            <div className="custom-timeline-item-label">
              {`${displayDate(item?.created_at)} ${displayTime(item?.created_at)}`}
            </div>
          </li>
        );
      })}
    </ul>

    {leadDetailById?.is_transferred === 1 && (
      <div style={{ marginTop: 16, borderTop: '1px solid #f0f0f0', paddingTop: 16 }}>
        <div style={{ fontWeight: 600, marginBottom: 12, color: '#1677ff', fontSize: 14 }}>Transfer History</div>
        {transferLoading ? (
          <Spin size="small" style={{ display: 'block', textAlign: 'center', padding: 16 }} />
        ) : transferHistory.length === 0 ? (
          <Empty description="No transfer history" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <Timeline
            items={transferHistory.map((item) => ({
              dot: <SwapOutlined style={{ color: '#fa8c16' }} />,
              children: (
                <div key={item.id}>
                  <div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 2 }}>
                    {displayDate(item.created_at)} {displayTime(item.created_at)}
                  </div>
                  <div>
                    Transferred from <strong>{item.from_employee_name} ({item.from_launch_name})</strong> → <strong>{item.to_employee_name} ({item.to_launch_name})</strong>
                    {' '}by <strong>{item.transferred_by_name}</strong>
                  </div>
                  <Tag color="orange" style={{ marginTop: 4, fontSize: 11 }}>
                    {item.transfer_type === 'self_transfer' ? 'Self Transfer' : 'Lead Transfer'}
                  </Tag>
                  {item.remark && (
                    <div style={{ marginTop: 4, color: '#595959', fontSize: 13 }}>
                      <em>{item.remark}</em>
                    </div>
                  )}
                </div>
              ),
            }))}
          />
        )}
      </div>
    )}
    </>
  );
});

RemarkPanel.displayName = 'RemarkPanel';
export default RemarkPanel;
