/**
 * Single Site Selector
 * Site-only selector without "All Sites" option
 * For pages that require a specific site selection (Automation, Content Settings)
 */
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Dropdown } from '../ui/dropdown/Dropdown';
import { DropdownItem } from '../ui/dropdown/DropdownItem';
import { fetchSites, Site, setActiveSite as apiSetActiveSite } from '../../services/api';
import { useToast } from '../ui/toast/ToastContainer';
import { useSiteStore } from '../../store/siteStore';
import { useAuthStore } from '../../store/authStore';
import Button from '../ui/button/Button';

export default function SingleSiteSelector() {
  const toast = useToast();
  const navigate = useNavigate();
  const { activeSite, setActiveSite, loadActiveSite } = useSiteStore();
  const { user, refreshUser, isAuthenticated } = useAuthStore();
  
  // Site switcher state
  const [sitesOpen, setSitesOpen] = useState(false);
  const [sites, setSites] = useState<Site[]>([]);
  const [sitesLoading, setSitesLoading] = useState(true);
  const siteButtonRef = useRef<HTMLButtonElement>(null);
  const noSitesAvailable = !sitesLoading && sites.length === 0;

  // Load sites
  useEffect(() => {
    if (isAuthenticated && user) {
      refreshUser().catch((error) => {
        console.debug('SingleSiteSelector: Failed to refresh user (non-critical):', error);
      });
    }
  }, [isAuthenticated]);

  useEffect(() => {
    loadSites();
    if (!activeSite) {
      loadActiveSite();
    }
  }, [user?.account?.id]);

  const loadSites = async () => {
    try {
      setSitesLoading(true);
      const response = await fetchSites();
      const activeSites = (response.results || []).filter(site => site.is_active);
      setSites(activeSites);
    } catch (error: any) {
      console.error('Failed to load sites:', error);
      toast.error(`Failed to load sites: ${error.message}`);
    } finally {
      setSitesLoading(false);
    }
  };

  const handleSiteSelect = async (siteId: number) => {
    try {
      await apiSetActiveSite(siteId);
      const selectedSite = sites.find(s => s.id === siteId);
      if (selectedSite) {
        setActiveSite(selectedSite);
        toast.success(`Switched to "${selectedSite.name}"`);
      }
      setSitesOpen(false);
    } catch (error: any) {
      toast.error(`Failed to switch site: ${error.message}`);
    }
  };

  // Get display text
  const getSiteDisplayText = () => {
    if (sitesLoading) return 'Loading...';
    return activeSite?.name || 'Select Site';
  };

  // Check if a site is selected
  const isSiteSelected = (siteId: number) => {
    return activeSite?.id === siteId;
  };

  const handleCreateSite = () => navigate('/sites');

  if (sitesLoading && sites.length === 0) {
    return (
      <div className="text-sm text-gray-500 dark:text-gray-400">
        Loading sites...
      </div>
    );
  }

  if (noSitesAvailable) {
    return (
      <div className="flex flex-col sm:flex-row sm:items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
        <span>No active sites yet.</span>
        <Button size="sm" variant="primary" onClick={handleCreateSite}>
          Create Site
        </Button>
      </div>
    );
  }

  return (
    <div className="relative inline-block">
      <button
        ref={siteButtonRef}
        onClick={() => setSitesOpen(!sitesOpen)}
        className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-brand-200 rounded-lg hover:bg-brand-50 hover:border-brand-300 dark:bg-gray-800 dark:text-gray-300 dark:border-brand-700/50 dark:hover:bg-brand-500/10 dark:hover:border-brand-600/50 transition-colors dropdown-toggle"
        aria-label="Switch site"
        disabled={sitesLoading || sites.length === 0}
      >
        <span className="flex items-center gap-2">
          <svg
            className="w-4 h-4 text-brand-500 dark:text-brand-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
            />
          </svg>
          <span className="max-w-[150px] truncate">
            {getSiteDisplayText()}
          </span>
        </span>
        <svg
          className={`w-4 h-4 text-brand-500 dark:text-brand-400 transition-transform ${sitesOpen ? 'rotate-180' : ''}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>

      <Dropdown
        isOpen={sitesOpen}
        onClose={() => setSitesOpen(false)}
        anchorRef={siteButtonRef}
        placement="bottom-left"
        className="w-64 p-2"
      >
        {sites.map((site) => (
          <DropdownItem
            key={site.id}
            onItemClick={() => handleSiteSelect(site.id)}
            className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
              isSiteSelected(site.id)
                ? "bg-brand-50 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
                : "text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"
            }`}
          >
            <span className="flex-1">{site.name}</span>
            {isSiteSelected(site.id) && (
              <svg
                className="w-4 h-4 text-brand-600 dark:text-brand-400"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                  clipRule="evenodd"
                />
              </svg>
            )}
          </DropdownItem>
        ))}
      </Dropdown>
    </div>
  );
}
