import React, { useEffect, useMemo, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  StatusBar,
  ScrollView,
  Switch,
  Alert,
  Linking,
  ActivityIndicator,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import { useAuthStore } from "@/stores/auth";
import { api } from "@/lib/api";
import { useUser } from "@/providers/UserProvider";
import {
  User,
  Bell,
  Moon,
  Shield,
  HelpCircle,
  Info,
  MessageSquare,
  LogOut,
  ChevronRight,
  Smartphone,
  Globe,
  Lock,
  Heart,
  Trash2,
} from "lucide-react-native";
import { router } from "expo-router";
import {
  PRIMARY,
  PRIMARY_DARK,
  PRIMARY_LIGHT,
} from "@/constants/colors";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";
import {
  hasOrganizationBillingAccess,
  shouldShowInAppBillingPaywall,
  useOrganizationBilling,
} from "@/hooks/organization";
import { BillingPaywall } from "@/components/BillingPaywall";
import {
  canUseInAppPurchases,
  getBillingPackageOptions,
  isPurchaseCancelledError,
  purchaseBillingPackage,
  restoreBillingPurchases,
  type BillingPackageOption,
} from "@/lib/purchases";

export default function SettingsScreen() {
  const signOut = useAuthStore((state) => state.signOut);
  const user = useUser();
  const colorScheme = useColorScheme();
  const organizationBillingQuery = useOrganizationBilling();

  // Theme-aware colors
  const backgroundColor = useThemeColor({ light: "#f8fafc", dark: "#111827" }, "background");
  const cardBackgroundColor = useThemeColor({ light: "#ffffff", dark: "#1f2937" }, "background");
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");
  const subtitleColor = useThemeColor({ light: "#6b7280", dark: "#9ca3af" }, "text");
  const borderColor = colorScheme === "dark" ? "#374151" : "#e5e7eb";

  // Theme-aware gradient colors
  const gradientColors: [string, string, string] =
    colorScheme === "dark"
      ? ["#2F2548", "#4B3384", PRIMARY_DARK]
      : [PRIMARY_DARK, PRIMARY, PRIMARY_LIGHT];

  // Settings state
  const [pushNotifications, setPushNotifications] = useState(true);
  const [emailNotifications, setEmailNotifications] = useState(true);
  const [biometricAuth, setBiometricAuth] = useState(false);
  const [billingPackages, setBillingPackages] = useState<BillingPackageOption[]>([]);
  const [billingError, setBillingError] = useState<string | null>(null);
  const [isLoadingPackages, setIsLoadingPackages] = useState(false);
  const [isPurchasing, setIsPurchasing] = useState(false);
  const [isRestoring, setIsRestoring] = useState(false);
  const [isSyncingBilling, setIsSyncingBilling] = useState(false);
  const isDeletingAccount = React.useRef(false);

  const organizationBilling = organizationBillingQuery.data;
  const hasBillingAccess = organizationBilling
    ? hasOrganizationBillingAccess(organizationBilling)
    : false;
  const canShowInAppPaywall = organizationBilling
    ? shouldShowInAppBillingPaywall(organizationBilling)
    : false;

  const visibleBillingPackages = useMemo(() => {
    if (!organizationBilling) {
      return [];
    }

    return billingPackages.filter((pkg) =>
      organizationBilling.required_plan === "team" ? pkg.plan === "annual" : true
    );
  }, [billingPackages, organizationBilling]);

  useEffect(() => {
    let cancelled = false;

    const loadBillingPackages = async () => {
      if (!user.id || !canShowInAppPaywall || !canUseInAppPurchases()) {
        setBillingPackages([]);
        setBillingError(null);
        setIsLoadingPackages(false);
        return;
      }

      setBillingError(null);
      setIsLoadingPackages(true);

      try {
        const packages = await getBillingPackageOptions(user.id);
        if (!cancelled) {
          setBillingPackages(packages);
        }
      } catch (error) {
        console.error("Failed to load RevenueCat packages:", error);
        if (!cancelled) {
          setBillingError(
            "Impossible de charger les offres Apple pour le moment. Réessayez dans quelques instants."
          );
        }
      } finally {
        if (!cancelled) {
          setIsLoadingPackages(false);
        }
      }
    };

    loadBillingPackages();

    return () => {
      cancelled = true;
    };
  }, [canShowInAppPaywall, user.id]);

  const handleSignOut = () => {
    Alert.alert("Déconnexion", "Êtes-vous sûr de vouloir vous déconnecter ?", [
      {
        text: "Annuler",
        style: "cancel",
      },
      {
        text: "Se déconnecter",
        style: "destructive",
        onPress: signOut,
      },
    ]);
  };

  const handleContactSupport = () => {
    Linking.openURL("mailto:support@xtablo.com?subject=Support XTablo");
  };

  const handleDeleteAccount = () => {
    Alert.alert(
      "Supprimer le compte",
      "Cette action est irréversible. Votre compte et toutes vos données seront définitivement supprimés. Êtes-vous sûr de vouloir continuer ?",
      [
        { text: "Annuler", style: "cancel" },
        {
          text: "Supprimer mon compte",
          style: "destructive",
          onPress: async () => {
            if (isDeletingAccount.current) return;
            isDeletingAccount.current = true;
            try {
              const session = useAuthStore.getState().session;
              if (!session) {
                Alert.alert("Erreur", "Session expirée. Veuillez vous reconnecter.");
                return;
              }
              await api.delete("/api/v1/users/me", {
                headers: { Authorization: `Bearer ${session.access_token}` },
                timeout: 15000,
              });
              await signOut();
            } catch (error) {
              console.error("Account deletion error:", error);
              Alert.alert(
                "Erreur",
                "Une erreur est survenue lors de la suppression de votre compte. Veuillez réessayer."
              );
            } finally {
              isDeletingAccount.current = false;
            }
          },
        },
      ]
    );
  };

  const handleRateApp = () => {
    // Replace with your actual app store URL
    Alert.alert(
      "Évaluer l'application",
      "Vous aimez XTablo ? Laissez-nous un avis sur l'App Store !",
      [
        { text: "Plus tard", style: "cancel" },
        { text: "Évaluer", onPress: () => console.log("Rate app") },
      ]
    );
  };

  const renderSettingsSection = (title: string, children: React.ReactNode) => (
    <View style={styles.section}>
      <Text style={[styles.sectionTitle, { color: subtitleColor }]}>{title}</Text>
      <View style={[styles.sectionContent, { backgroundColor: cardBackgroundColor, borderColor }]}>
        {children}
      </View>
    </View>
  );

  const renderSettingsItem = (
    icon: React.ReactNode,
    title: string,
    subtitle?: string,
    onPress?: () => void,
    rightComponent?: React.ReactNode,
    showArrow: boolean = true
  ) => (
    <TouchableOpacity
      style={[styles.settingsItem, { borderBottomColor: borderColor }]}
      onPress={onPress}
      disabled={!onPress}
      activeOpacity={onPress ? 0.7 : 1}
    >
      <View style={styles.settingsItemLeft}>
        <View style={styles.iconContainer}>{icon}</View>
        <View style={styles.settingsItemContent}>
          <Text style={[styles.settingsItemTitle, { color: textColor }]}>{title}</Text>
          {subtitle && (
            <Text style={[styles.settingsItemSubtitle, { color: subtitleColor }]}>{subtitle}</Text>
          )}
        </View>
      </View>
      <View style={styles.settingsItemRight}>
        {rightComponent}
        {showArrow && onPress && (
          <ChevronRight size={20} color={subtitleColor} style={{ marginLeft: 8 }} />
        )}
      </View>
    </TouchableOpacity>
  );

  const renderSwitchItem = (
    icon: React.ReactNode,
    title: string,
    subtitle: string,
    value: boolean,
    onValueChange: (value: boolean) => void
  ) =>
    renderSettingsItem(
      icon,
      title,
      subtitle,
      undefined,
      <Switch
        value={value}
        onValueChange={onValueChange}
        trackColor={{
          false: colorScheme === "dark" ? "#374151" : "#e5e7eb",
          true: PRIMARY,
        }}
        thumbColor={value ? "#ffffff" : "#ffffff"}
        ios_backgroundColor={colorScheme === "dark" ? "#374151" : "#e5e7eb"}
      />,
      false
    );

  const waitForBillingSync = async () => {
    setIsSyncingBilling(true);
    setBillingError(null);

    try {
      for (let attempt = 0; attempt < 6; attempt += 1) {
        const result = await organizationBillingQuery.refetch();
        if (result.data && hasOrganizationBillingAccess(result.data)) {
          return true;
        }

        if (attempt < 5) {
          await new Promise((resolve) => setTimeout(resolve, 2000));
        }
      }

      setBillingError(
        "L'achat a bien ete recu, mais la synchronisation serveur prend plus de temps que prevu."
      );
      return false;
    } finally {
      setIsSyncingBilling(false);
    }
  };

  const handlePurchase = async (pkg: BillingPackageOption) => {
    if (!user.id || isPurchasing || isSyncingBilling) {
      return;
    }

    setBillingError(null);
    setIsPurchasing(true);

    try {
      await purchaseBillingPackage(user.id, pkg.package);
      await waitForBillingSync();
    } catch (error) {
      if (!isPurchaseCancelledError(error)) {
        console.error("Apple purchase failed:", error);
        setBillingError("Le paiement Apple a echoue. Merci de reessayer.");
      }
    } finally {
      setIsPurchasing(false);
    }
  };

  const handleRestorePurchases = async () => {
    if (!user.id || isRestoring || isSyncingBilling) {
      return;
    }

    setBillingError(null);
    setIsRestoring(true);

    try {
      await restoreBillingPurchases(user.id);
      await waitForBillingSync();
    } catch (error) {
      console.error("Apple restore failed:", error);
      setBillingError("La restauration des achats a echoue. Merci de reessayer.");
    } finally {
      setIsRestoring(false);
    }
  };

  const renderBillingContent = () => {
    if (organizationBillingQuery.isLoading) {
      return (
        <View style={styles.billingBox}>
          <ActivityIndicator />
          <Text style={[styles.billingHelperText, { color: subtitleColor }]}>
            Chargement de votre statut d&apos;abonnement…
          </Text>
        </View>
      );
    }

    if (organizationBillingQuery.error || !organizationBilling) {
      return (
        <View style={styles.billingBox}>
          <Text style={styles.billingErrorText}>
            Impossible de charger la facturation de l&apos;organisation.
          </Text>
        </View>
      );
    }

    if (hasBillingAccess && organizationBilling.active_subscription_plan) {
      const subscriptionLabel =
        organizationBilling.active_subscription_plan === "annual"
          ? "Annuel"
          : organizationBilling.active_subscription_plan === "team"
            ? "Equipe"
            : "Solo";

      return renderSettingsItem(
        <Shield size={20} color={PRIMARY} />,
        "Abonnement actif",
        `${subscriptionLabel} • ${organizationBilling.organization.name}`,
        undefined,
        undefined,
        false
      );
    }

    if (hasBillingAccess && !organizationBilling.is_trial_expired) {
      const trialEndsAt = new Date(organizationBilling.trial_ends_at).toLocaleDateString("fr-FR", {
        day: "numeric",
        month: "long",
      });

      return renderSettingsItem(
        <Shield size={20} color={PRIMARY} />,
        "Essai actif",
        `Votre acces d'essai reste actif jusqu'au ${trialEndsAt}.`,
        undefined,
        undefined,
        false
      );
    }

    if (!canUseInAppPurchases()) {
      return (
        <View style={styles.billingBox}>
          <Text style={[styles.billingHelperText, { color: subtitleColor }]}>
            Les achats integres ne sont disponibles que sur iPhone avec une build de developpement
            native.
          </Text>
        </View>
      );
    }

    return (
      <View style={styles.billingBox}>
        <BillingPaywall
          canManageBillingInApp={canShowInAppPaywall}
          errorMessage={
            visibleBillingPackages.length === 0 &&
            !isLoadingPackages &&
            !billingError &&
            canShowInAppPaywall
              ? "Aucune offre Apple n'est disponible pour ce compte pour le moment."
              : billingError
          }
          isLoadingPackages={isLoadingPackages || isPurchasing}
          isRestoring={isRestoring}
          isSyncing={isSyncingBilling}
          onPurchase={handlePurchase}
          onRestore={handleRestorePurchases}
          packages={visibleBillingPackages}
          requiredPlan={organizationBilling.required_plan}
        />
      </View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor }]}>
      <StatusBar
        barStyle={colorScheme === "dark" ? "light-content" : "light-content"}
        backgroundColor={gradientColors[0]}
      />

      {/* Header */}
      <LinearGradient
        colors={gradientColors}
        style={styles.headerGradient}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <View style={styles.headerContent}>
          <Text style={styles.headerTitle}>Paramètres</Text>
          <Text style={styles.headerSubtitle}>Gérez vos préférences et votre compte</Text>
        </View>

        {/* Decorative Elements */}
        <View style={styles.decorativeCircle1} />
        <View style={styles.decorativeCircle2} />
      </LinearGradient>

      <ScrollView
        style={[styles.content, { backgroundColor }]}
        showsVerticalScrollIndicator={false}
      >
        {renderSettingsSection(
          "Compte",
          <>
            {renderSettingsItem(
              <User size={20} color={PRIMARY} />,
              "Profil utilisateur",
              `${user.name || "Non défini"} • ${user.email}`,
              () => router.push("/user"),
              undefined,
              true
            )}
          </>
        )}

        {renderSettingsSection("Abonnement", renderBillingContent())}

        {/* {renderSettingsSection(
          "Notifications",
          <>
            {renderSwitchItem(
              <Bell size={20} color="#10b981" />,
              "Notifications push",
              "Recevoir des notifications sur votre appareil",
              pushNotifications,
              setPushNotifications
            )}
            {renderSwitchItem(
              <Smartphone size={20} color="#10b981" />,
              "Notifications par email",
              "Recevoir des notifications par email",
              emailNotifications,
              setEmailNotifications
            )}
          </>
        )} */}

        {/* Appearance Section */}
        {renderSettingsSection(
          "Apparence",
          <>
            {renderSwitchItem(
              <Moon size={20} color="#6366f1" />,
              "Mode sombre",
              "Thème système automatique",
              colorScheme === "dark",
              () => {
                Alert.alert(
                  "Thème automatique",
                  "Le thème suit automatiquement les préférences de votre appareil. Modifiez le thème dans les paramètres de votre appareil."
                );
              }
            )}
          </>
        )}

        {/* {renderSettingsSection(
          "Sécurité et confidentialité",
          <>
            {renderSwitchItem(
              <Lock size={20} color="#ef4444" />,
              "Authentification biométrique",
              "Utiliser votre empreinte ou Face ID",
              biometricAuth,
              setBiometricAuth
            )}
            {renderSettingsItem(
              <Shield size={20} color="#ef4444" />,
              "Politique de confidentialité",
              "Consulter notre politique de confidentialité",
              () => Linking.openURL("https://xtablo.com/privacy-policy"),
              undefined,
              true
            )}
          </>
        )} */}

        {/* Help & Support Section */}
        {renderSettingsSection(
          "Aide et support",
          <>
            {/* {renderSettingsItem(
              <HelpCircle size={20} color="#f59e0b" />,
              "Centre d'aide",
              "FAQ et guides d'utilisation",
              () => Linking.openURL("https://xtablo.com/help"),
              undefined,
              true
            )} */}
            {renderSettingsItem(
              <MessageSquare size={20} color="#f59e0b" />,
              "Contacter le support",
              "Envoyez-nous un email",
              handleContactSupport,
              undefined,
              true
            )}
            {/* {renderSettingsItem(
              <Heart size={20} color="#ec4899" />,
              "Évaluer l'application",
              "Aidez-nous à améliorer XTablo",
              handleRateApp,
              undefined,
              true
            )} */}
          </>
        )}

        {/* About Section */}
        {renderSettingsSection(
          "À propos",
          <>
            {renderSettingsItem(
              <Info size={20} color="#6b7280" />,
              "Version de l'application",
              "1.0.0 (Build 1)",
              undefined,
              undefined,
              false
            )}
            {/* {renderSettingsItem(
              <Globe size={20} color="#6b7280" />,
              "Site web",
              "Visitez notre site web",
              () => Linking.openURL("https://app.xtablo.com"),
              undefined,
              true
            )} */}
          </>
        )}

        {/* Danger Zone Section */}
        {renderSettingsSection(
          "Zone de danger",
          <>
            {renderSettingsItem(
              <Trash2 size={20} color="#ef4444" />,
              "Supprimer le compte",
              "Supprimer définitivement votre compte et vos données",
              handleDeleteAccount,
              undefined,
              true
            )}
          </>
        )}

        {/* Sign Out Section */}
        <View style={styles.signOutSection}>
          <TouchableOpacity
            style={styles.signOutButton}
            onPress={handleSignOut}
            activeOpacity={0.8}
          >
            <LinearGradient
              colors={["#ef4444", "#dc2626"]}
              style={styles.signOutGradient}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <LogOut size={20} color="white" />
              <Text style={styles.signOutText}>Se déconnecter</Text>
            </LinearGradient>
          </TouchableOpacity>
        </View>

        {/* Bottom Spacing */}
        <View style={styles.bottomSpacing} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  headerGradient: {
    paddingTop: 50,
    paddingBottom: 25,
    paddingHorizontal: 20,
    position: "relative",
    overflow: "hidden",
  },
  headerContent: {
    zIndex: 10,
  },
  headerTitle: {
    fontSize: 28,
    color: "white",
    fontWeight: "bold",
    marginBottom: 4,
  },
  headerSubtitle: {
    fontSize: 16,
    color: "rgba(255, 255, 255, 0.8)",
    fontWeight: "400",
  },
  decorativeCircle1: {
    position: "absolute",
    top: -50,
    right: -30,
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: "rgba(255, 255, 255, 0.1)",
  },
  decorativeCircle2: {
    position: "absolute",
    bottom: -20,
    left: -20,
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: "rgba(255, 255, 255, 0.08)",
  },
  content: {
    flex: 1,
    marginTop: -10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    paddingTop: 20,
  },
  section: {
    marginBottom: 24,
    paddingHorizontal: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 12,
    marginLeft: 4,
  },
  sectionContent: {
    borderRadius: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 3,
    overflow: "hidden",
    borderWidth: 1,
  },
  settingsItem: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
  },
  settingsItemLeft: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
  },
  iconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "rgba(0, 0, 0, 0.05)",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  settingsItemContent: {
    flex: 1,
  },
  settingsItemTitle: {
    fontSize: 16,
    fontWeight: "500",
    marginBottom: 2,
  },
  settingsItemSubtitle: {
    fontSize: 14,
  },
  settingsItemRight: {
    flexDirection: "row",
    alignItems: "center",
  },
  signOutSection: {
    paddingHorizontal: 20,
    marginTop: 20,
    marginBottom: 20,
  },
  signOutButton: {
    borderRadius: 16,
    shadowColor: "#ef4444",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 6,
  },
  signOutGradient: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 16,
    paddingHorizontal: 24,
    borderRadius: 16,
  },
  signOutText: {
    color: "white",
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 8,
  },
  bottomSpacing: {
    height: 100,
  },
  billingBox: {
    paddingHorizontal: 20,
    paddingVertical: 20,
  },
  billingErrorText: {
    color: "#b91c1c",
    fontSize: 14,
    lineHeight: 20,
  },
  billingHelperText: {
    fontSize: 14,
    lineHeight: 20,
    marginTop: 10,
  },
});
