import { useState, useEffect } from "react";
import {
  createOrganizationConfig,
  updateOrganizationConfig,
  getOrganizationConfig,
  OrganizationConfig,
  OrganizationConfigListResponse,
} from "@/shared/services/organizationConfigService";
import { toast } from "sonner";
import { Switch } from "@/shared/common/ui/switch";
import { useTranslation } from "react-i18next";

interface VisibilityCellProps {
  organizationId: string;
}

export const VisibilityCell = ({ organizationId }: VisibilityCellProps) => {
  const { t } = useTranslation();
  const [config, setConfig] = useState<OrganizationConfig | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isInitialLoading, setIsInitialLoading] = useState(true);

  // Load organization configuration
  useEffect(() => {
    const loadConfig = async () => {
      try {
        setIsInitialLoading(true);
        const response = await getOrganizationConfig(organizationId);

        // Handle the new response format with count and items
        const responseData = response.data as OrganizationConfigListResponse;

        if (
          responseData.count > 0 &&
          responseData.items &&
          responseData.items.length > 0
        ) {
          // Take the first configuration item
          const configData = responseData.items[0];
          setConfig(configData);
        } else {
          // No config found - organization is visible by default
          setConfig(null);
        }
      } catch (error) {
        // If API call fails, assume no config exists (visible by default)
        console.warn(
          `Failed to load config for organization ${organizationId}:`,
          error
        );
        setConfig(null);
      } finally {
        setIsInitialLoading(false);
      }
    };

    loadConfig();
  }, [organizationId]);

  // Handle visibility toggle
  const handleVisibilityToggle = async (canReceive: boolean) => {
    try {
      setIsLoading(true);

      const payload = {
        canStartReceivingRecord: canReceive,
        organizationId: organizationId,
      };

      // Simple logic: if we have both ID and organization ID, use PUT; if only organization ID, use POST
      if (config && config.id) {
        // We have both ID and organization ID - use PUT request
        await updateOrganizationConfig(config.id, payload);
        setConfig((prev: OrganizationConfig | null) =>
          prev ? { ...prev, canStartReceivingRecord: canReceive } : null
        );
      } else {
        // We only have organization ID - use POST request
        const response = await createOrganizationConfig(payload);
        setConfig(response.data);
      }

      toast.success(
        canReceive
          ? t("organization.visibilityEnabled")
          : t("organization.visibilityDisabled")
      );
    } catch (error) {
      console.error("Error updating organization visibility:", error);
      toast.error(t("organization.visibilityUpdateFailed"));
    } finally {
      setIsLoading(false);
    }
  };

  // Don't render until we have real data from API
  if (isInitialLoading) {
    return (
      <div className="flex items-center justify-center">
        <div className="w-4 h-4 border-2 border-gray-300 dark:border-gray-600 border-t-primary-600 rounded-full animate-spin"></div>
      </div>
    );
  }

  // Show real API result: if config exists, use its value; if no config, organization is visible by default
  const isVisible = config ? config.canStartReceivingRecord : true;

  return (
    <div className="flex items-center gap-3">
      <div className="flex items-center gap-2">
        <span className="text-sm text-gray-600 dark:text-gray-300">
          {isVisible ? t("organization.visible") : t("organization.hidden")}
        </span>
        <Switch
          checked={isVisible}
          onCheckedChange={handleVisibilityToggle}
          disabled={isLoading}
          className="data-[state=checked]:bg-primary-600"
        />
      </div>
      {isLoading && (
        <div className="w-4 h-4 border-2 border-gray-300 dark:border-gray-600 border-t-primary-600 rounded-full animate-spin"></div>
      )}
    </div>
  );
};
