import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Shield, ShieldCheck, ShieldAlert, Info, Loader2, Database, Cloud, Ban } from "lucide-react";
import { API_URL } from "@/lib/config";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";

// GDPR Compliance: Check if settings should be hidden
const HIDE_ORDERS_ACCESS_SETTINGS = import.meta.env.VITE_HIDE_ORDERS_ACCESS_SETTINGS === 'true';
const HIDE_CUSTOMERS_ACCESS_SETTINGS = import.meta.env.VITE_HIDE_CUSTOMERS_ACCESS_SETTINGS === 'true';

type DataAccessPolicy = 'sync' | 'api_only' | 'not_allowed';

interface DataAccessPermissions {
  allow_customer_access: boolean;
  allow_order_access: boolean;
  allow_product_access: boolean;
}

interface AccessPolicySettings {
  products_access_policy: DataAccessPolicy;
  customers_access_policy: DataAccessPolicy;
  orders_access_policy: DataAccessPolicy;
}

interface DataAccessSettingsProps {
  storeId: string;
  storeName: string;
  currentPermissions: DataAccessPermissions;
  currentPolicies?: AccessPolicySettings;
  onPermissionsUpdated?: (newPermissions: DataAccessPermissions) => void;
  onPoliciesUpdated?: (newPolicies: AccessPolicySettings) => void;
}

export function DataAccessSettings({
  storeId,
  storeName,
  currentPermissions,
  currentPolicies,
  onPermissionsUpdated,
  onPoliciesUpdated
}: DataAccessSettingsProps) {
  const { t } = useTranslation();

  // Initialize with new policy-based system if available, otherwise convert from old permissions
  const [policies, setPolicies] = useState<AccessPolicySettings>(
    currentPolicies || {
      products_access_policy: currentPermissions.allow_product_access ? 'sync' : 'not_allowed',
      customers_access_policy: currentPermissions.allow_customer_access ? 'sync' : 'not_allowed',
      orders_access_policy: currentPermissions.allow_order_access ? 'sync' : 'not_allowed'
    }
  );
  const [saving, setSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const { toast } = useToast();

  const handlePolicyChange = (dataType: 'products' | 'customers' | 'orders', policy: DataAccessPolicy) => {
    setPolicies(prev => ({
      ...prev,
      [`${dataType}_access_policy`]: policy
    }));
    setHasChanges(true);
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/api/stores/${storeId}/access-policies`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(policies)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to update access policies');
      }

      toast({
        title: t('integrations.dataAccessSettings.toast.successTitle'),
        description: t('integrations.dataAccessSettings.toast.successDescription'),
      });

      setHasChanges(false);
      if (onPoliciesUpdated) {
        onPoliciesUpdated(policies);
      }
    } catch (error) {
      console.error('Error updating access policies:', error);
      toast({
        title: t('integrations.dataAccessSettings.toast.errorTitle'),
        description: error instanceof Error ? error.message : t('integrations.dataAccessSettings.toast.errorDescription'),
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    setPolicies(currentPolicies || {
      products_access_policy: currentPermissions.allow_product_access ? 'sync' : 'not_allowed',
      customers_access_policy: currentPermissions.allow_customer_access ? 'sync' : 'not_allowed',
      orders_access_policy: currentPermissions.allow_order_access ? 'sync' : 'not_allowed'
    });
    setHasChanges(false);
  };

  const getSecurityLevel = () => {
    // Only count policies for visible settings
    const visiblePolicies = [
      policies.products_access_policy,
      ...(!HIDE_CUSTOMERS_ACCESS_SETTINGS ? [policies.customers_access_policy] : []),
      ...(!HIDE_ORDERS_ACCESS_SETTINGS ? [policies.orders_access_policy] : [])
    ];

    const notAllowedCount = visiblePolicies.filter(p => p === 'not_allowed').length;
    const apiOnlyCount = visiblePolicies.filter(p => p === 'api_only').length;
    const totalVisible = visiblePolicies.length;

    // When all settings are hidden except products, show based on products only
    if (totalVisible === 1) {
      if (policies.products_access_policy === 'not_allowed') return { level: "maximum", icon: ShieldCheck, color: "text-green-500", label: t('integrations.dataAccessSettings.securityLevel.maximumPrivacy') };
      if (policies.products_access_policy === 'api_only') return { level: "high", icon: ShieldCheck, color: "text-green-400", label: t('integrations.dataAccessSettings.securityLevel.highPrivacy') };
      return { level: "full", icon: ShieldAlert, color: "text-orange-500", label: t('integrations.dataAccessSettings.securityLevel.fullSync') };
    }

    if (notAllowedCount === totalVisible) return { level: "maximum", icon: ShieldCheck, color: "text-green-500", label: t('integrations.dataAccessSettings.securityLevel.maximumPrivacy') };
    if (notAllowedCount >= totalVisible - 1) return { level: "high", icon: ShieldCheck, color: "text-green-400", label: t('integrations.dataAccessSettings.securityLevel.highPrivacy') };
    if (notAllowedCount >= 1 || apiOnlyCount >= totalVisible - 1) return { level: "medium", icon: Shield, color: "text-yellow-500", label: t('integrations.dataAccessSettings.securityLevel.mediumPrivacy') };
    if (apiOnlyCount >= 1) return { level: "balanced", icon: Shield, color: "text-blue-500", label: t('integrations.dataAccessSettings.securityLevel.balanced') };
    return { level: "full", icon: ShieldAlert, color: "text-orange-500", label: t('integrations.dataAccessSettings.securityLevel.fullSync') };
  };

  const security = getSecurityLevel();
  const SecurityIcon = security.icon;

  const renderPolicyOptions = (dataType: 'products' | 'customers' | 'orders', policyKey: keyof AccessPolicySettings, isPII: boolean = false, isDisabled: boolean = false) => {
    return (
      <RadioGroup
        value={policies[policyKey]}
        onValueChange={(value) => handlePolicyChange(dataType, value as DataAccessPolicy)}
        className="space-y-3 mt-3"
        disabled={isDisabled}
      >
        <div className={`flex items-start space-x-3 p-3 rounded-md bg-slate-600/30 ${isDisabled ? 'opacity-60 cursor-not-allowed' : 'hover:bg-slate-600/50'} transition-colors`}>
          <RadioGroupItem value="sync" id={`${dataType}-sync`} className="mt-1" disabled={saving || isDisabled} />
          <Label htmlFor={`${dataType}-sync`} className={`flex-1 ${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
            <div className="flex items-center gap-2 mb-1">
              <Database className="w-4 h-4 text-cyan-400" />
              <span className="text-white font-medium">{t('integrations.dataAccessSettings.accessModes.syncCache.title')}</span>
              <Badge variant="outline" className="text-xs border-cyan-500 text-cyan-400">{t('integrations.dataAccessSettings.accessModes.syncCache.badge')}</Badge>
            </div>
            <p className="text-xs text-slate-400">
              {t('integrations.dataAccessSettings.accessModes.syncCache.description')}
            </p>
          </Label>
        </div>

        <div className={`flex items-start space-x-3 p-3 rounded-md bg-slate-600/30 ${isDisabled ? 'opacity-60 cursor-not-allowed' : 'hover:bg-slate-600/50'} transition-colors`}>
          <RadioGroupItem value="api_only" id={`${dataType}-api`} className="mt-1" disabled={saving || isDisabled} />
          <Label htmlFor={`${dataType}-api`} className={`flex-1 ${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
            <div className="flex items-center gap-2 mb-1">
              <Cloud className="w-4 h-4 text-blue-400" />
              <span className="text-white font-medium">{t('integrations.dataAccessSettings.accessModes.apiOnly.title')}</span>
              {isPII && <Badge variant="outline" className="text-xs border-green-500 text-green-400">{t('integrations.dataAccessSettings.accessModes.apiOnly.badge')}</Badge>}
            </div>
            <p className="text-xs text-slate-400">
              {t('integrations.dataAccessSettings.accessModes.apiOnly.description')}
            </p>
          </Label>
        </div>

        <div className={`flex items-start space-x-3 p-3 rounded-md bg-slate-600/30 ${isDisabled ? 'opacity-60 cursor-not-allowed' : 'hover:bg-slate-600/50'} transition-colors`}>
          <RadioGroupItem value="not_allowed" id={`${dataType}-none`} className="mt-1" disabled={saving || isDisabled} />
          <Label htmlFor={`${dataType}-none`} className={`flex-1 ${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
            <div className="flex items-center gap-2 mb-1">
              <Ban className="w-4 h-4 text-red-400" />
              <span className="text-white font-medium">{t('integrations.dataAccessSettings.accessModes.noAccess.title')}</span>
              <Badge variant="outline" className="text-xs border-red-500 text-red-400">{t('integrations.dataAccessSettings.accessModes.noAccess.badge')}</Badge>
            </div>
            <p className="text-xs text-slate-400">
              {t('integrations.dataAccessSettings.accessModes.noAccess.description')}
            </p>
          </Label>
        </div>
      </RadioGroup>
    );
  };

  return (
    <Card className="bg-slate-800 border-slate-700">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-white flex items-center gap-2">
              <SecurityIcon className={`w-5 h-5 ${security.color}`} />
              {t('integrations.dataAccessSettings.title')}
            </CardTitle>
            <CardDescription className="text-slate-400">
              {t('integrations.dataAccessSettings.description', { storeName })}
            </CardDescription>
          </div>
          <Badge className={`${security.color.replace('text-', 'bg-')} text-white`}>
            {security.label}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* GDPR Notice */}
        <Alert className="bg-blue-500/10 border-blue-500/50">
          <Info className="h-4 w-4 text-blue-400" />
          <AlertDescription className="text-blue-300 text-sm">
            <strong>{t('integrations.dataAccessSettings.gdprNotice.title')}</strong> {t('integrations.dataAccessSettings.gdprNotice.description')}
          </AlertDescription>
        </Alert>

        {/* Notice when PII settings are hidden for GDPR compliance */}
        {(HIDE_CUSTOMERS_ACCESS_SETTINGS || HIDE_ORDERS_ACCESS_SETTINGS) && (
          <Alert className="bg-green-500/10 border-green-500/50">
            <ShieldCheck className="h-4 w-4 text-green-400" />
            <AlertDescription className="text-green-300 text-sm">
              <strong>{t('integrations.dataAccessSettings.gdprProtection.title')}</strong> {t('common.personalData')} (
              {[
                HIDE_CUSTOMERS_ACCESS_SETTINGS && t('integrations.dataAccessSettings.gdprProtection.customerData'),
                HIDE_ORDERS_ACCESS_SETTINGS && t('integrations.dataAccessSettings.gdprProtection.orderData')
              ].filter(Boolean).join(` ${t('integrations.dataAccessSettings.gdprProtection.and')} `)}
              ) {t('integrations.dataAccessSettings.gdprProtection.description')}
            </AlertDescription>
          </Alert>
        )}

        {/* Policy Settings */}
        <div className="space-y-6">
          {/* Products Access - Always enabled, store owners cannot change this */}
          <div className="p-4 bg-slate-700/50 rounded-lg border border-slate-600">
            <div className="flex items-center gap-2 mb-2">
              <h4 className="text-white font-medium">{t('integrations.dataAccessSettings.productData.title')}</h4>
              <Badge variant="outline" className="text-xs border-blue-500 text-blue-400">
                {t('integrations.dataAccessSettings.productData.badgePublic')}
              </Badge>
              <Badge variant="outline" className="text-xs border-slate-500 text-slate-400">
                {t('integrations.dataAccessSettings.productData.badgeRequired')}
              </Badge>
            </div>
            <p className="text-sm text-slate-400 mb-3">
              {t('integrations.dataAccessSettings.productData.description')}
            </p>
            {renderPolicyOptions('products', 'products_access_policy', false, true)}
          </div>

          {/* Customers Access - Hidden when VITE_HIDE_CUSTOMERS_ACCESS_SETTINGS is true */}
          {!HIDE_CUSTOMERS_ACCESS_SETTINGS && (
            <div className="p-4 bg-slate-700/50 rounded-lg border border-slate-600">
              <div className="flex items-center gap-2 mb-2">
                <h4 className="text-white font-medium">{t('integrations.dataAccessSettings.customerData.title')}</h4>
                <Badge variant="outline" className="text-xs border-orange-500 text-orange-400">
                  {t('integrations.dataAccessSettings.customerData.badgePII')}
                </Badge>
              </div>
              <p className="text-sm text-slate-400 mb-3">
                {t('integrations.dataAccessSettings.customerData.description')}
              </p>
              {renderPolicyOptions('customers', 'customers_access_policy', true)}
            </div>
          )}

          {/* Orders Access - Hidden when VITE_HIDE_ORDERS_ACCESS_SETTINGS is true */}
          {!HIDE_ORDERS_ACCESS_SETTINGS && (
            <div className="p-4 bg-slate-700/50 rounded-lg border border-slate-600">
              <div className="flex items-center gap-2 mb-2">
                <h4 className="text-white font-medium">{t('integrations.dataAccessSettings.orderData.title')}</h4>
                <Badge variant="outline" className="text-xs border-orange-500 text-orange-400">
                  {t('integrations.dataAccessSettings.orderData.badgePII')}
                </Badge>
              </div>
              <p className="text-sm text-slate-400 mb-3">
                {t('integrations.dataAccessSettings.orderData.description')}
              </p>
              {renderPolicyOptions('orders', 'orders_access_policy', true)}
            </div>
          )}
        </div>

        {/* Action Buttons */}
        {hasChanges && (
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-slate-700">
            <Button
              variant="outline"
              onClick={handleReset}
              disabled={saving}
              className="text-slate-400 border-slate-600 hover:bg-slate-700"
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={saving}
              className="bg-cyan-500 hover:bg-cyan-600 text-white"
            >
              {saving ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Saving...
                </>
              ) : (
                'Save Changes'
              )}
            </Button>
          </div>
        )}

        {/* Privacy level warnings */}
        {security.level === 'maximum' && (
          <Alert className="bg-green-500/10 border-green-500/50">
            <ShieldCheck className="h-4 w-4 text-green-400" />
            <AlertDescription className="text-green-300 text-sm">
              <strong>Maximum Privacy:</strong> All data access is blocked. API tools will not be able to access any store data.
            </AlertDescription>
          </Alert>
        )}

        {/* Only show api_only alert for visible settings */}
        {((!HIDE_CUSTOMERS_ACCESS_SETTINGS && policies.customers_access_policy === 'api_only') ||
          (!HIDE_ORDERS_ACCESS_SETTINGS && policies.orders_access_policy === 'api_only')) && (
          <Alert className="bg-blue-500/10 border-blue-500/50">
            <Info className="h-4 w-4 text-blue-400" />
            <AlertDescription className="text-blue-300 text-sm">
              <strong>API-Only Mode Active:</strong> Selected data types will be fetched directly from your store on demand.
              This is slower but ensures no personal data is cached locally, making it GDPR-friendly.
            </AlertDescription>
          </Alert>
        )}
      </CardContent>
    </Card>
  );
}
