/**
 * Combined Site and Sector Selector Component
 * Displays both site switcher and sector selector side by side with accent colors
 */
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router';
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 { useSectorStore } from '../../store/sectorStore';
import { useAuthStore } from '../../store/authStore';
import Button from '../ui/button/Button';

interface SiteAndSectorSelectorProps {
  hideSectorSelector?: boolean;
}

export default function SiteAndSectorSelector({
  hideSectorSelector = false,
}: SiteAndSectorSelectorProps) {
  const toast = useToast();
  const navigate = useNavigate();
  const { activeSite, setActiveSite, loadActiveSite } = useSiteStore();
  const { activeSector, sectors, setActiveSector, loading: sectorsLoading } = useSectorStore();
  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);
  
  // Sector selector state
  const [sectorsOpen, setSectorsOpen] = useState(false);
  const sectorButtonRef = useRef<HTMLButtonElement>(null);
  const noSitesAvailable = !sitesLoading && sites.length === 0;

  // Load sites
  useEffect(() => {
    if (isAuthenticated && user) {
      refreshUser().catch((error) => {
        console.debug('SiteAndSectorSelector: 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}`);
    }
  };

  const handleSectorSelect = (sectorId: number | null) => {
    if (sectorId === null) {
      setActiveSector(null);
      setSectorsOpen(false);
    } else {
      const sector = sectors.find(s => s.id === sectorId);
      if (sector) {
        setActiveSector(sector);
        setSectorsOpen(false);
      }
    }
  };

  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. Create a site to unlock planner and writer modules.</span>
        <Button size="sm" variant="primary" onClick={handleCreateSite}>
          Create Site
        </Button>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-3">
      {/* Site Switcher */}
      <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">
              {sitesLoading ? 'Loading...' : activeSite?.name || 'Select Site'}
            </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 ${
                activeSite?.id === 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>
              {activeSite?.id === 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>

      {/* Sector Selector */}
      {!hideSectorSelector && (
        <div className="relative inline-block">
          {!activeSite ? (
            <div className="px-3 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 rounded-lg">
              Select a site to choose sectors
            </div>
          ) : sectorsLoading ? (
            <div className="px-3 py-2 text-sm text-gray-500 dark:text-gray-400 border border-brand-200 rounded-lg">
              Loading sectors...
            </div>
          ) : sectors.length === 0 ? (
            <div className="px-3 py-2 text-sm text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 rounded-lg">
              This site has no sectors yet.
            </div>
          ) : (
            <>
              <button
                ref={sectorButtonRef}
                onClick={() => setSectorsOpen(!sectorsOpen)}
                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="Select sector"
                disabled={sectorsLoading || sectors.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="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
                    />
                  </svg>
                  <span className="max-w-[150px] truncate">
                    {activeSector?.name || 'All Sectors'}
                  </span>
                </span>
                <svg
                  className={`w-4 h-4 text-brand-500 dark:text-brand-400 transition-transform ${sectorsOpen ? '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={sectorsOpen}
                onClose={() => setSectorsOpen(false)}
                anchorRef={sectorButtonRef}
                placement="bottom-right"
                className="w-64 p-2 overflow-y-auto max-h-[300px]"
              >
                {/* "All Sectors" option */}
                <DropdownItem
                  onItemClick={() => handleSectorSelect(null)}
                  className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
                    !activeSector
                      ? "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">All Sectors</span>
                  {!activeSector && (
                    <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>
                {sectors.map((sector) => (
                  <DropdownItem
                    key={sector.id}
                    onItemClick={() => handleSectorSelect(sector.id)}
                    className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
                      activeSector?.id === sector.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">{sector.name}</span>
                    {activeSector?.id === sector.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>
      )}
    </div>
  );
}

