import { useEffect, useState, useCallback } from "react";
import { View, Text, TouchableOpacity, Alert, ScrollView } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router, useFocusEffect } from "expo-router";
import { MaterialIcons } from "@expo/vector-icons";
import {
  loadCodexAuth,
  clearCodexAuth,
  loadClaudeSessionKey,
  clearClaudeSessionKey,
} from "@/lib/storage";
import { resetOnboarding } from "@/lib/setupState";
import type { CodexAuth } from "@/types/codex";
import Constants from "expo-constants";

function SettingRow({
  icon,
  label,
  value,
  onPress,
  destructive,
  disabled,
}: {
  icon: React.ComponentProps<typeof MaterialIcons>["name"];
  label: string;
  value?: string;
  onPress?: () => void;
  destructive?: boolean;
  disabled?: boolean;
}) {
  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      activeOpacity={onPress ? 0.7 : 1}
      className="flex-row items-center gap-x-3 py-3.5 px-4"
    >
      <View className="w-8 items-center">
        <MaterialIcons
          name={icon}
          size={20}
          color={destructive ? "#ef4444" : disabled ? "#a3a3a3" : "#737373"}
        />
      </View>
      <View className="flex-1">
        <Text
          className={`text-sm font-medium ${
            destructive
              ? "text-red-500"
              : disabled
              ? "text-neutral-400 dark:text-neutral-600"
              : "text-neutral-800 dark:text-neutral-100"
          }`}
        >
          {label}
        </Text>
        {value && (
          <Text className="text-xs text-neutral-400 dark:text-neutral-500 mt-0.5 font-mono">
            {value}
          </Text>
        )}
      </View>
      {onPress && !disabled && (
        <MaterialIcons
          name="chevron-right"
          size={18}
          color={destructive ? "#ef4444" : "#d4d4d4"}
        />
      )}
    </TouchableOpacity>
  );
}

function SectionHeader({ title }: { title: string }) {
  return (
    <Text className="text-xs font-semibold uppercase tracking-widest text-neutral-400 dark:text-neutral-500 px-4 pt-5 pb-1.5">
      {title}
    </Text>
  );
}

function SectionCard({ children }: { children: React.ReactNode }) {
  return (
    <View className="bg-white dark:bg-neutral-900 rounded-2xl border border-neutral-200 dark:border-neutral-800 mx-4 overflow-hidden">
      {children}
    </View>
  );
}

function Divider() {
  return (
    <View className="ml-16 mr-0 h-px bg-neutral-100 dark:bg-neutral-800" />
  );
}

export default function SettingsTab() {
  const [codexAuth, setCodexAuth] = useState<CodexAuth | null>(null);
  const [claudeKey, setClaudeKey] = useState<string | null>(null);

  const reload = useCallback(() => {
    Promise.all([loadCodexAuth(), loadClaudeSessionKey()]).then(
      ([codex, claude]) => {
        setCodexAuth(codex);
        setClaudeKey(claude);
      }
    );
  }, []);

  useEffect(() => {
    reload();
  }, [reload]);

  useFocusEffect(useCallback(() => {
    reload();
  }, [reload]));

  const handleClearCodex = () => {
    Alert.alert(
      "Clear Codex credentials",
      "This will remove your stored auth.json data. You can re-import it anytime.",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Clear",
          style: "destructive",
          onPress: async () => {
            await clearCodexAuth();
            setCodexAuth(null);
          },
        },
      ]
    );
  };

  const handleClearClaude = () => {
    Alert.alert(
      "Clear Claude session key",
      "Your session key will be removed. You can re-enter it anytime.",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Clear",
          style: "destructive",
          onPress: async () => {
            await clearClaudeSessionKey();
            setClaudeKey(null);
          },
        },
      ]
    );
  };

  const handleResetSetup = () => {
    Alert.alert(
      "Re-run Setup Wizard",
      "This will clear all credentials and restart the setup flow.",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Reset & Re-run",
          style: "destructive",
          onPress: async () => {
            await Promise.all([
              clearCodexAuth(),
              clearClaudeSessionKey(),
              resetOnboarding(),
            ]);
            router.replace("/onboarding");
          },
        },
      ]
    );
  };

  const appVersion = Constants.expoConfig?.version ?? "1.0.0";

  return (
    <SafeAreaView
      className="flex-1 bg-neutral-50 dark:bg-neutral-950"
      edges={["top", "bottom"]}
    >
      <ScrollView className="flex-1" contentContainerStyle={{ paddingBottom: 48 }}>
        {/* Header */}
        <View className="px-4 py-5">
          <Text className="text-2xl font-bold text-neutral-900 dark:text-white tracking-tight">
            Settings
          </Text>
        </View>

        {/* Codex CLI section */}
        <SectionHeader title="Codex CLI" />
        <SectionCard>
          {codexAuth ? (
            <>
              <SettingRow
                icon="check-circle"
                label="Connected"
                value={codexAuth.accountId ? `${codexAuth.accountId.slice(0, 16)}…` : undefined}
                disabled
              />
              <Divider />
              <SettingRow
                icon="delete-outline"
                label="Clear credentials"
                onPress={handleClearCodex}
                destructive
              />
            </>
          ) : (
            <SettingRow
              icon="upload-file"
              label="Import auth.json"
              onPress={() => router.navigate("/(tabs)/codex")}
            />
          )}
        </SectionCard>

        {/* Claude.ai section */}
        <SectionHeader title="Claude.ai" />
        <SectionCard>
          {claudeKey ? (
            <>
              <SettingRow
                icon="check-circle"
                label="Connected"
                value={`${claudeKey.slice(0, 16)}…`}
                disabled
              />
              <Divider />
              <SettingRow
                icon="delete-outline"
                label="Clear session key"
                onPress={handleClearClaude}
                destructive
              />
            </>
          ) : (
            <SettingRow
              icon="vpn-key"
              label="Enter session key"
              onPress={() => router.navigate("/(tabs)/claude")}
            />
          )}
        </SectionCard>

        {/* App section */}
        <SectionHeader title="App" />
        <SectionCard>
          <SettingRow
            icon="info-outline"
            label="Version"
            value={appVersion}
            disabled
          />
          <Divider />
          <SettingRow
            icon="restart-alt"
            label="Re-run Setup Wizard"
            onPress={handleResetSetup}
            destructive
          />
        </SectionCard>
      </ScrollView>
    </SafeAreaView>
  );
}
