import React, { useEffect, useRef, useState } from 'react';
import { Button, notification, Select, Typography } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import useDebounce from '@/hooks/useDebounce';
import { getCampaigns, refreshGoogleCampaigns } from '../service';
import type { GoogleCampaign } from '../interface';

/*
  Google Ads counterpart of CampaignSelect.tsx — same shape, same pagination/
  search pattern, but calls the Google campaigns endpoint instead of
  Facebook's. Kept as its own component rather than a shared one so each
  source's picker can diverge later without touching the other.

  The list is read from the campaigns the backend has saved — it never calls
  Google, so opening it costs no Google quota. Each campaign carries its
  microsite. The Refresh button is what asks Google for fresh campaigns and
  microsites.
 */
interface GoogleCampaignSelectProps {
  placeholder?: string;
  value?: string;
  valueLabel?: string;
  disabled?: boolean;
  onSelect?: (campaign: GoogleCampaign | undefined) => void;
  onTotalChange?: (total: number) => void;
  onFirstLoad?: () => void;
}

const GoogleCampaignSelect: React.FC<GoogleCampaignSelectProps> = ({
  placeholder = 'Select a campaign',
  value: controlledValue,
  valueLabel,
  disabled,
  onSelect,
  onTotalChange,
  onFirstLoad,
}) => {
  const [campaigns, setCampaigns] = useState<GoogleCampaign[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [value, setValue] = useState<string | undefined>(controlledValue);
  const [refreshing, setRefreshing] = useState(false);
  const [lastRefreshedAt, setLastRefreshedAt] = useState<string | null>(null);
  const loadMoreLock = useRef(false);
  const skipNextReset = useRef(false);
  const firstLoadFired = useRef(false);

  const debouncedSearch = useDebounce(searchQuery, 400);

  const fetchCampaigns = (search: string, nextPage: number): Promise<GoogleCampaign[]> => {
    setLoading(true);
    return getCampaigns('google', { search, page: nextPage, pageSize: 50 })
      .then((res: any) => {
        const body = res?.data || {};
        const list: GoogleCampaign[] = body.data || [];
        setPage(body.page || nextPage);
        setHasMore(!!body.hasMore);
        onTotalChange?.(body.total ?? list.length);
        setCampaigns((prev) => (nextPage === 1 ? list : [...prev, ...list]));
        if (nextPage === 1) setLastRefreshedAt(body.last_refreshed_at || null);
        return list;
      })
      .catch(() => [] as GoogleCampaign[])
      .finally(() => {
        setLoading(false);
        loadMoreLock.current = false;
        if (!firstLoadFired.current) {
          firstLoadFired.current = true;
          onFirstLoad?.();
        }
      });
  };

  useEffect(() => {
    if (controlledValue !== undefined) {
      setValue(controlledValue);
      skipNextReset.current = true;
    }
  }, [controlledValue]);

  useEffect(() => {
    fetchCampaigns(debouncedSearch, 1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearch]);

  // Asks Google for fresh campaigns and microsites, then reloads the list. If Google refuses (its daily
  // quota can run out), the saved list stays as it was and the user is told why.
  const handleRefresh = async (): Promise<void> => {
    setRefreshing(true);
    try {
      const res = await refreshGoogleCampaigns();
      const body = res?.data || {};
      const unreadable = (body.failed_accounts?.length || 0) + (body.microsite_failed_accounts?.length || 0);
      const description = `${body.campaigns ?? 0} campaigns and ${body.microsites_found ?? 0} microsites updated.${unreadable ? ' Some accounts could not be read from Google; their saved data is unchanged.' : ''}`;
      if (unreadable) {
        notification.warning({ message: 'Google campaigns refreshed', description });
      } else {
        notification.success({ message: 'Google campaigns refreshed', description });
      }
    } catch (err: any) {
      const body = err?.response?.data;
      notification.warning({
        message: body?.rate_limited ? 'Google limit reached' : 'Could not refresh from Google',
        description: body?.message || 'Showing the saved campaigns.',
      });
    } finally {
      const list = await fetchCampaigns(searchQuery, 1);
      // The campaign picked in the form holds an older copy of itself: hand it the fresh one (its microsite may have changed).
      const picked = value ? list.find((c) => c.campaign_id === value) : undefined;
      if (picked) onSelect?.(picked);
      setRefreshing(false);
    }
  };

  const handlePopupScroll = (e: React.UIEvent<HTMLDivElement>): void => {
    const { currentTarget } = e;
    const reachedBottom = currentTarget.scrollTop + currentTarget.clientHeight >= currentTarget.scrollHeight - 5;
    if (reachedBottom && hasMore && !loading && !loadMoreLock.current) {
      loadMoreLock.current = true;
      fetchCampaigns(searchQuery, page + 1);
    }
  };

  const options = campaigns.map((c) => ({ value: c.campaign_id, label: c.name }));
  const mergedOptions =
    value && valueLabel && !campaigns.some((c) => c.campaign_id === value)
      ? [{ value, label: valueLabel }, ...options]
      : options;

  return (
    <div>
      <div className="flex items-center gap-2 mt-1">
        <Select
          style={{ flex: 1, minWidth: 0 }}
          showSearch
          allowClear
          disabled={disabled}
          loading={loading}
          placeholder={placeholder}
          value={value}
          filterOption={false}
          onSearch={setSearchQuery}
          onPopupScroll={handlePopupScroll}
          onChange={(selectedValue) => {
            setValue(selectedValue);
            if (!selectedValue) {
              onSelect?.(undefined);
              return;
            }
            const campaign = campaigns.find((c) => c.campaign_id === selectedValue);
            onSelect?.(campaign);
          }}
          options={mergedOptions}
        />
        <Button icon={<ReloadOutlined />} loading={refreshing} disabled={disabled || refreshing} onClick={handleRefresh}>
        </Button>
      </div>
      <Typography.Text type="secondary" style={{ fontSize: 11 }}>
        {lastRefreshedAt ? `Campaigns and microsites last refreshed ${new Date(lastRefreshedAt).toLocaleString()}` : 'Not refreshed from Google yet'}
      </Typography.Text>
    </div>
  );
};

export default GoogleCampaignSelect;
