import React, { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';

import {
  listCampaigns,
  deleteCampaign,
  activateCampaign,
  pauseCampaign,
  resumeCampaign,
  completeCampaign,
} from '../service/campaigns/campaigns.service';
import type { ICampaign } from '../service/campaigns/campaigns.interface';

const STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-100 text-green-800',
  paused: 'bg-yellow-100 text-yellow-800',
  building: 'bg-blue-100 text-blue-800',
  draft: 'bg-gray-100 text-gray-800',
  completed: 'bg-gray-100 text-gray-800',
  failed: 'bg-red-100 text-red-800',
};

const Campaigns = (): JSX.Element => {
  const navigate = useNavigate();

  const [campaigns, setCampaigns] = useState<ICampaign[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchCampaigns = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await listCampaigns();
      if (!response.errors && response.data) {
        setCampaigns(response.data.campaigns || []);
      }
    } catch (err: any) {
      setError(err?.message || 'Failed to load campaigns');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchCampaigns();
  }, [fetchCampaigns]);

  // The Reco copilot dispatches ``copilot:data-changed`` after a turn where a
  // write tool ran (create_campaign, activate/pause/complete, etc.). WordPress
  // has no route loaders to revalidate, so this page re-fetches its list when
  // the event fires - mirroring the Remix ``revalidator.revalidate()`` the
  // copilot used in the Shopify plugin. The building-status poll below then
  // takes over for any campaign still indexing. The listener is removed on
  // unmount so it never fires against a stale component.
  useEffect(() => {
    const onCopilotDataChanged = (): void => {
      void fetchCampaigns();
    };
    window.addEventListener('copilot:data-changed', onCopilotDataChanged);

    return () => {
      window.removeEventListener('copilot:data-changed', onCopilotDataChanged);
    };
  }, [fetchCampaigns]);

  // Poll while any campaign is building
  useEffect(() => {
    const hasBuilding = campaigns.some(c => c.status === 'building');
    if (!hasBuilding) return;

    const interval = setInterval(() => {
      fetchCampaigns();
    }, 5000);

    return () => clearInterval(interval);
  }, [campaigns, fetchCampaigns]);

  const handleAction = async (
    campaignId: string,
    action: 'activate' | 'pause' | 'resume' | 'complete' | 'delete',
    e: React.MouseEvent
  ) => {
    e.stopPropagation();

    const actions = {
      activate: activateCampaign,
      pause: pauseCampaign,
      resume: resumeCampaign,
      complete: completeCampaign,
      delete: deleteCampaign,
    };

    try {
      setActionLoading(campaignId);
      await actions[action](campaignId);
      await fetchCampaigns();
    } catch (err: any) {
      setError(err?.message || `Failed to ${action} campaign`);
    } finally {
      setActionLoading(null);
    }
  };

  const activeCampaign = campaigns.find(c => c.status === 'active');

  return (
    <div className="w-full max-w-5xl mx-auto p-5">
      <div className="space-y-5">
        <div className="flex justify-between items-center">
          <h1 className="text-xl font-bold text-gray-900">Campaigns</h1>
          <button
            className="px-4 py-2 bg-gray-900 text-white text-sm font-medium rounded-lg hover:bg-gray-800 transition-colors"
            onClick={() => navigate('/campaigns/create')}
          >
            Create Campaign
          </button>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex justify-between items-center">
            <p className="text-sm">{error}</p>
            <button
              className="text-red-500 hover:text-red-700 text-sm"
              onClick={() => setError(null)}
            >
              Dismiss
            </button>
          </div>
        )}

        {activeCampaign && (
          <div className="bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-lg">
            <p className="text-sm">
              Active campaign: <strong>{activeCampaign.name}</strong> -{' '}
              {activeCampaign.indexed_product_count} products indexed
            </p>
          </div>
        )}

        {loading ? (
          <div className="flex justify-center py-10">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
          </div>
        ) : campaigns.length === 0 ? (
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <p className="text-sm text-gray-500">
              No campaigns yet. Create your first campaign to boost specific
              product categories in chat conversations.
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {campaigns.map(campaign => (
              <div
                key={campaign.campaign_id}
                className="cursor-pointer bg-white rounded-xl border border-gray-200 p-5 hover:border-gray-300 hover:shadow-sm transition-all"
                onClick={() => navigate(`/campaigns/${campaign.campaign_id}`)}
              >
                <div className="space-y-3">
                  <div className="flex justify-between items-center flex-wrap gap-2">
                    <div className="flex items-center gap-2 flex-wrap">
                      <h2 className="text-base font-semibold text-gray-900">
                        {campaign.name}
                      </h2>
                      <span
                        className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[campaign.status] || 'bg-gray-100 text-gray-800'}`}
                      >
                        {campaign.status}
                      </span>
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                        {campaign.priority}
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      {campaign.status === 'draft' && (
                        <button
                          className="px-3 py-1 text-xs font-medium bg-gray-900 text-white rounded-lg hover:bg-gray-800 disabled:opacity-50"
                          disabled={actionLoading === campaign.campaign_id}
                          onClick={e =>
                            handleAction(campaign.campaign_id, 'activate', e)
                          }
                        >
                          {actionLoading === campaign.campaign_id
                            ? '...'
                            : 'Activate'}
                        </button>
                      )}
                      {campaign.status === 'active' && (
                        <button
                          className="px-3 py-1 text-xs font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                          disabled={actionLoading === campaign.campaign_id}
                          onClick={e =>
                            handleAction(campaign.campaign_id, 'pause', e)
                          }
                        >
                          {actionLoading === campaign.campaign_id
                            ? '...'
                            : 'Pause'}
                        </button>
                      )}
                      {campaign.status === 'paused' && (
                        <button
                          className="px-3 py-1 text-xs font-medium bg-gray-900 text-white rounded-lg hover:bg-gray-800 disabled:opacity-50"
                          disabled={actionLoading === campaign.campaign_id}
                          onClick={e =>
                            handleAction(campaign.campaign_id, 'resume', e)
                          }
                        >
                          {actionLoading === campaign.campaign_id
                            ? '...'
                            : 'Resume'}
                        </button>
                      )}
                      {['active', 'paused'].includes(campaign.status) && (
                        <button
                          className="px-3 py-1 text-xs font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                          disabled={actionLoading === campaign.campaign_id}
                          onClick={e =>
                            handleAction(campaign.campaign_id, 'complete', e)
                          }
                        >
                          {actionLoading === campaign.campaign_id
                            ? '...'
                            : 'Complete'}
                        </button>
                      )}
                      {['draft', 'failed', 'completed'].includes(
                        campaign.status
                      ) && (
                        <button
                          className="px-3 py-1 text-xs font-medium bg-white border border-red-300 text-red-600 rounded-lg hover:bg-red-50 disabled:opacity-50"
                          disabled={actionLoading === campaign.campaign_id}
                          onClick={e =>
                            handleAction(campaign.campaign_id, 'delete', e)
                          }
                        >
                          {actionLoading === campaign.campaign_id
                            ? '...'
                            : 'Delete'}
                        </button>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center gap-4 flex-wrap">
                    <span className="text-sm text-gray-500">
                      Categories: {campaign.target_categories.join(', ')}
                    </span>
                    {campaign.indexed_product_count > 0 && (
                      <span className="text-sm text-gray-500">
                        {campaign.indexed_product_count} products indexed
                      </span>
                    )}
                  </div>

                  {campaign.report && (
                    <div className="flex items-center gap-4 flex-wrap">
                      <span className="text-xs text-gray-600">
                        {campaign.report.impressions} impressions
                      </span>
                      <span className="text-xs text-gray-600">
                        {campaign.report.clicks} clicks
                      </span>
                      <span className="text-xs text-gray-600">
                        {campaign.report.add_to_cart} add to cart
                      </span>
                      <span className="text-xs text-gray-600">
                        CTR: {campaign.report.ctr}%
                      </span>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Campaigns;
