'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { FiGrid } from 'react-icons/fi';
import ImageWithFallback from '@/Component/Common/ImageWithFallback';
import { SliderLeftSVG, SliderRightSVG } from '@/Component/Common/SVGs/CommonSVG';
import { parseCampaignAttachment } from '@/Utils/Other/campaignAttachment';

type CampaignStripProps = {
  campaigns: any[];
  selectedCampaignId: string | 'all';
  translations: any;
  campaignPath?: string;
  allCampaignsTotal: number;
  allCampaignsUnread: number;
  getCampaignConversationCount: (campaign: any) => number;
  getCampaignUnreadCount: (campaign: any) => number;
  onSelectAll: () => void;
  onSelectCampaign: (campaign: any) => void;
};

const CampaignStrip = (props: CampaignStripProps) => {
  const {
    campaigns,
    selectedCampaignId,
    translations,
    campaignPath,
    allCampaignsTotal,
    allCampaignsUnread,
    getCampaignConversationCount,
    getCampaignUnreadCount,
    onSelectAll,
    onSelectCampaign,
  } = props;

  const campaignScrollRef = useRef<HTMLDivElement>(null);
  const [campaignScrollState, setCampaignScrollState] = useState({
    hasOverflow: false,
    canScrollLeft: false,
    canScrollRight: false,
  });

  const updateCampaignScrollState = useCallback(() => {
    const el = campaignScrollRef.current;
    if (!el) return;
    const hasOverflow = el.scrollWidth > el.clientWidth + 1;
    setCampaignScrollState({
      hasOverflow,
      canScrollLeft: hasOverflow && el.scrollLeft > 0,
      canScrollRight: hasOverflow && el.scrollLeft + el.clientWidth < el.scrollWidth - 1,
    });
  }, []);

  const scrollCampaignsBy = useCallback((direction: 'left' | 'right') => {
    campaignScrollRef.current?.scrollBy({
      left: direction === 'left' ? -240 : 240,
      behavior: 'smooth',
    });
  }, []);

  /** Keep the selected campaign card centered in the horizontal strip */
  const scrollSelectedIntoCenter = useCallback(() => {
    const container = campaignScrollRef.current;
    if (!container) return;

    const selectedEl = container.querySelector(
      `[data-campaign-id="${CSS.escape(String(selectedCampaignId))}"]`
    ) as HTMLElement | null;

    if (!selectedEl) return;

    const containerRect = container.getBoundingClientRect();
    const selectedRect = selectedEl.getBoundingClientRect();
    const selectedCenter =
      selectedRect.left - containerRect.left + container.scrollLeft + selectedRect.width / 2;
    const targetScroll = selectedCenter - container.clientWidth / 2;

    container.scrollTo({
      left: Math.max(0, targetScroll),
      behavior: 'smooth',
    });
  }, [selectedCampaignId]);

  useEffect(() => {
    const el = campaignScrollRef.current;
    if (!el) return;
    updateCampaignScrollState();
    const onScroll = () => updateCampaignScrollState();
    el.addEventListener('scroll', onScroll, { passive: true });
    const resizeObserver = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateCampaignScrollState) : null;
    resizeObserver?.observe(el);
    window.addEventListener('resize', updateCampaignScrollState);
    return () => {
      el.removeEventListener('scroll', onScroll);
      resizeObserver?.disconnect();
      window.removeEventListener('resize', updateCampaignScrollState);
    };
  }, [campaigns, updateCampaignScrollState]);

  // After campaigns load / selection changes (e.g. from campaign detail URL), center the active card
  useEffect(() => {
    if (!campaigns.length && selectedCampaignId !== 'all') return;
    const frame = requestAnimationFrame(() => {
      scrollSelectedIntoCenter();
      window.setTimeout(updateCampaignScrollState, 400);
    });
    return () => cancelAnimationFrame(frame);
  }, [selectedCampaignId, campaigns, scrollSelectedIntoCenter, updateCampaignScrollState]);

  const getCampaignBannerSrc = (campaign: any) => {
    const firstAttachment = campaign?.attachment?.[0];
    if (!firstAttachment) return null;
    const { fileName } = parseCampaignAttachment(firstAttachment);
    if (!fileName) return null;
    if (/^https?:\/\//i.test(fileName)) return fileName;
    return campaignPath ? `${campaignPath}${fileName}` : fileName;
  };

  return (
    <div className="relative flex items-center gap-1.5 min-w-0 flex-1 overflow-hidden">
      {campaignScrollState.hasOverflow && campaignScrollState.canScrollLeft && (
        <button
          type="button"
          aria-label="Scroll campaigns left"
          onClick={() => scrollCampaignsBy('left')}
          className="shrink-0 z-10 flex items-center justify-center w-8 h-8 rounded-full border border-lightGray bg-white hover:border-primary/40 shadow-sm absolute left-0"
        >
          <SliderLeftSVG customClass="w-5 h-5" />
        </button>
      )}

      <div
        ref={campaignScrollRef}
        className="flex items-center gap-3 overflow-x-auto scrollbar-hide min-w-0 flex-1"
      >
        <button
          type="button"
          data-campaign-id="all"
          onClick={onSelectAll}
          className={`shrink-0 flex items-center gap-2 rounded-xl border px-3 py-2 min-w-[140px] ${
            selectedCampaignId === 'all' ? 'border-primary bg-primary/5' : 'border-lightGray bg-white'
          }`}
        >
          <span className="lg:w-12 lg:h-12 w-10 h-10 rounded-full bg-neutral-100 flex items-center justify-center">
            <FiGrid className="lg:w-5 lg:h-5 w-4 h-4" />
          </span>
          <div className="text-left relative">
            <div className="lg:text-sm text-xs font-semibold flex items-center gap-1.5">
              {translations?.all ?? 'All'}
              {allCampaignsUnread > 0 && (
                <span className="min-w-4 h-4 px-1 rounded-full bg-primary text-white text-[9px] flex items-center justify-center">
                  {allCampaignsUnread > 99 ? '99+' : allCampaignsUnread}
                </span>
              )}
            </div>
            <div className="lg:text-xs text-[10px] text-neutral-500">
              {allCampaignsTotal} {translations?.conversations ?? 'conversations'}
            </div>
          </div>
        </button>

        {campaigns.map((campaign: any) => {
          const bannerSrc = getCampaignBannerSrc(campaign);
          const campaignUnread = getCampaignUnreadCount(campaign);
          return (
            <button
              key={campaign.id}
              type="button"
              data-campaign-id={String(campaign.id)}
              onClick={() => onSelectCampaign(campaign)}
              className={`shrink-0 flex items-center gap-2 rounded-xl border px-3 py-2 min-w-[160px] max-w-[200px] ${
                String(selectedCampaignId) === String(campaign.id)
                  ? 'border-primary bg-primary/5'
                  : 'border-lightGray bg-white'
              }`}
            >
              <span className="relative lg:w-12 lg:h-12 w-10 h-10 rounded-full bg-primary/15 flex items-center justify-center text-primary font-bold shrink-0 text-lg">
                {bannerSrc ? (
                  <ImageWithFallback
                    src={bannerSrc}
                    alt={campaign.campaign_name || ''}
                    width={48}
                    height={48}
                    className="w-full h-full object-cover rounded-full"
                  />
                ) : (
                  (campaign.campaign_name || 'C').charAt(0).toUpperCase()
                )}
                {campaignUnread > 0 && (
                  <span className="absolute -top-0.5 -right-0.5 min-w-4 h-4 px-0.5 rounded-full bg-primary text-white text-[10px] flex items-center justify-center z-10">
                    {campaignUnread > 99 ? '99+' : campaignUnread}
                  </span>
                )}
              </span>
              <div className="text-left min-w-0">
                <div className="lg:text-sm text-xs font-semibold truncate">{campaign.campaign_name}</div>
                <div className="lg:text-xs text-[10px] text-neutral-500 truncate">
                  {getCampaignConversationCount(campaign)} {translations?.conversations ?? 'conversations'}
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {campaignScrollState.hasOverflow && campaignScrollState.canScrollRight && (
        <button
          type="button"
          aria-label="Scroll campaigns right"
          onClick={() => scrollCampaignsBy('right')}
          className="shrink-0 z-10 flex items-center justify-center w-8 h-8 rounded-full border border-lightGray bg-white hover:border-primary/40 shadow-sm absolute right-0"
        >
          <SliderRightSVG customClass="w-5 h-5" />
        </button>
      )}
    </div>
  );
};

export default CampaignStrip;
