import { useEffect, useState, useCallback } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  Alert,
  ScrollView,
  TextInput,
  Switch,
  KeyboardAvoidingView,
} 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,
  saveCodexAuth,
  loadClaudeSessionKey,
  clearClaudeSessionKey,
  saveClaudeSessionKey,
  saveClaudeLastActiveOrg,
  clearClaudeLastActiveOrg,
} from "@/lib/storage";
import { pickAndReadCodexAuth } from "@/lib/fileReader";
import { resetOnboarding } from "@/lib/setupState";
import { useNotificationSettings } from "@/hooks/useNotificationSettings";
import {
  isClaudeSessionKeyValid,
  validateClaudeSessionKey,
} from "@/lib/claudeCredentials";
import { COLORS } from "@/lib/constants";
import { formatTime, parseTimeInput } from "@/lib/timeUtils";
import { ScreenErrorBoundary } from "@/components/ScreenErrorBoundary";
import type { CodexAuth } from "@/types/codex";
import Constants from "expo-constants";

function humanizeImportError(code: string): string {
  if (code === "DOCUMENT_NOT_READABLE") {
    return "The selected file could not be read. Try copying auth.json into Files or Downloads and import it again.";
  }
  return code;
}
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" />;
}

function SettingsTabContent() {
  const [codexAuth, setCodexAuth] = useState<CodexAuth | null>(null);
  const [claudeKey, setClaudeKey] = useState<string | null>(null);
  const [pendingKey, setPendingKey] = useState("");
  const [pendingOrg, setPendingOrg] = useState("");
  const [claudeError, setClaudeError] = useState<string | null>(null);

  const notif = useNotificationSettings();
  const [timeInput, setTimeInput] = useState("");
  const [timeError, setTimeError] = useState<string | null>(null);
  const [thresholdInput, setThresholdInput] = useState("");

  // Sync local text inputs when settings load
  useEffect(() => {
    if (notif.loaded) {
      setTimeInput(formatTime(notif.settings.dailyHour, notif.settings.dailyMinute));
      setThresholdInput(String(notif.settings.thresholdPct));
    }
  }, [notif.loaded]);

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

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

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

  const handleImportCodex = async () => {
    try {
      const auth = await pickAndReadCodexAuth();
      await saveCodexAuth(auth);
      setCodexAuth(auth);
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : "UNKNOWN_ERROR";
      if (msg !== "PICKER_CANCELLED") {
        Alert.alert("Import failed", humanizeImportError(msg));
      }
    }
  };

  const handleSaveClaude = async () => {
    const trimmed = pendingKey.trim();
    const validationError = validateClaudeSessionKey(trimmed);
    if (validationError) {
      setClaudeError(validationError);
      return;
    }
    const orgTrimmed = pendingOrg.trim() || undefined;
    await saveClaudeSessionKey(trimmed);
    if (orgTrimmed) await saveClaudeLastActiveOrg(orgTrimmed);
    else await clearClaudeLastActiveOrg();
    setClaudeKey(trimmed);
    setPendingKey("");
    setPendingOrg("");
    setClaudeError(null);
  };

  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 handleTimeBlur = useCallback(() => {
    const parsed = parseTimeInput(timeInput);
    if (parsed) {
      void notif.update({ dailyHour: parsed.hour, dailyMinute: parsed.minute });
      setTimeInput(formatTime(parsed.hour, parsed.minute));
      setTimeError(null);
    } else {
      setTimeError("Use HH:MM format, from 00:00 to 23:59.");
    }
  }, [timeInput, notif]);

  const handleThresholdBlur = useCallback(() => {
    const n = parseInt(thresholdInput, 10);
    if (!isNaN(n) && n >= 1 && n <= 99) {
      void notif.update({ thresholdPct: n });
    } else {
      setThresholdInput(String(notif.settings.thresholdPct));
    }
  }, [thresholdInput, notif]);

  const canSaveClaude = isClaudeSessionKeyValid(pendingKey);
  const inlineClaudeError =
    claudeError ?? (pendingKey ? validateClaudeSessionKey(pendingKey) : null);
  const appVersion = Constants.expoConfig?.version ?? "1.0.0";

  return (
    <SafeAreaView
      className="flex-1 bg-neutral-50 dark:bg-neutral-950"
      edges={["top", "bottom"]}
    >
      <KeyboardAvoidingView
        className="flex-1"
        behavior={process.env.EXPO_OS === "ios" ? "padding" : "height"}
      >
        <ScrollView
          className="flex-1"
          contentContainerStyle={{ paddingBottom: 48 }}
          keyboardShouldPersistTaps="handled"
        >
          {/* 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={handleImportCodex}
              />
            )}
          </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
                />
              </>
            ) : (
              <View className="p-4">
                {inlineClaudeError && (
                  <Text selectable className="text-xs text-red-500 mb-2">
                    {inlineClaudeError}
                  </Text>
                )}
                <TextInput
                  value={pendingKey}
                  onChangeText={(t) => {
                    setPendingKey(t);
                    setClaudeError(null);
                  }}
                  placeholder="sk-ant-… (required)"
                  placeholderTextColor="#a3a3a3"
                  autoCapitalize="none"
                  autoCorrect={false}
                  secureTextEntry
                  className="border border-neutral-200 dark:border-neutral-700 rounded-xl px-3 py-3 text-sm text-neutral-900 dark:text-white bg-neutral-50 dark:bg-neutral-800 mb-2"
                />
                <TextInput
                  value={pendingOrg}
                  onChangeText={setPendingOrg}
                  placeholder="lastActiveOrg UUID (optional)"
                  placeholderTextColor="#a3a3a3"
                  autoCapitalize="none"
                  autoCorrect={false}
                  className="border border-neutral-200 dark:border-neutral-700 rounded-xl px-3 py-3 text-sm text-neutral-900 dark:text-white bg-neutral-50 dark:bg-neutral-800 mb-3"
                />
                <TouchableOpacity
                  onPress={handleSaveClaude}
                  disabled={!canSaveClaude}
                  className="py-3 px-4 rounded-xl items-center"
                  style={{
                    backgroundColor: canSaveClaude
                      ? COLORS.claude
                      : COLORS.disabled,
                  }}
                >
                  <Text
                    className="font-semibold text-sm"
                    style={{ color: canSaveClaude ? "white" : COLORS.muted }}
                  >
                    Save Session Key
                  </Text>
                </TouchableOpacity>
                <Text className="text-xs text-neutral-400 text-center mt-3 leading-relaxed">
                  Chrome DevTools → Application → Cookies → claude.ai →{" "}
                  <Text className="font-mono text-neutral-500">sessionKey</Text>
                </Text>
              </View>
            )}
          </SectionCard>

          {/* Notifications section */}
          <SectionHeader title="Notifications" />
          <SectionCard>
            {notif.permissionStatus !== "granted" ? (
              <TouchableOpacity
                onPress={async () => {
                  const granted = await notif.askPermissions();
                  if (!granted && notif.permissionStatus === "denied") {
                    Alert.alert(
                      "Notifications blocked",
                      "Go to Settings → CodexBar → Notifications to enable them."
                    );
                  }
                }}
                className="flex-row items-center gap-x-3 py-3.5 px-4"
              >
                <View className="w-8 items-center">
                  <MaterialIcons name="notifications-off" size={20} color="#737373" />
                </View>
                <View className="flex-1">
                  <Text className="text-sm font-medium text-neutral-800 dark:text-neutral-100">
                    Enable notifications
                  </Text>
                  <Text className="text-xs text-neutral-400 mt-0.5">
                    {notif.permissionStatus === "denied"
                      ? "Blocked — open system Settings to allow"
                      : "Required to receive alerts"}
                  </Text>
                </View>
                {notif.permissionStatus !== "denied" && (
                  <View className="px-2.5 py-1 rounded-full bg-amber-100 dark:bg-amber-900/30">
                    <Text className="text-xs font-semibold text-amber-700 dark:text-amber-300">
                      Allow
                    </Text>
                  </View>
                )}
              </TouchableOpacity>
            ) : (
              <>
                {/* Daily digest */}
                <View className="flex-row items-center gap-x-3 py-3.5 px-4">
                  <View className="w-8 items-center">
                    <MaterialIcons name="alarm" size={20} color="#737373" />
                  </View>
                  <View className="flex-1">
                    <Text className="text-sm font-medium text-neutral-800 dark:text-neutral-100">
                      Daily digest
                    </Text>
                    <Text className="text-xs text-neutral-400 mt-0.5">
                      Daily reminder with last-known usage
                    </Text>
                  </View>
                  <Switch
                    value={notif.settings.dailyEnabled}
                    onValueChange={(v) => void notif.update({ dailyEnabled: v })}
                    trackColor={{ false: COLORS.disabled, true: COLORS.codex }}
                    thumbColor="white"
                  />
                </View>

                {notif.settings.dailyEnabled && (
                  <>
                    <Divider />
                    <View className="px-4 py-3">
                      <View className="flex-row items-center gap-x-3">
                        <View className="w-8 items-center">
                          <MaterialIcons name="schedule" size={20} color="#737373" />
                        </View>
                        <Text className="flex-1 text-sm font-medium text-neutral-800 dark:text-neutral-100">
                          Time
                        </Text>
                        <TextInput
                          value={timeInput}
                          onChangeText={(value) => {
                            setTimeInput(value);
                            setTimeError(null);
                          }}
                          onBlur={handleTimeBlur}
                          placeholder="09:00"
                          placeholderTextColor={COLORS.muted}
                          keyboardType="numbers-and-punctuation"
                          returnKeyType="done"
                          maxLength={5}
                          className="text-sm font-mono text-neutral-600 dark:text-neutral-300 text-right"
                          style={{ minWidth: 52 }}
                        />
                      </View>
                      {timeError && (
                        <Text selectable className="ml-11 mt-1.5 text-xs text-red-500">
                          {timeError}
                        </Text>
                      )}
                    </View>
                  </>
                )}

                <Divider />

                {/* Threshold alert */}
                <View className="flex-row items-center gap-x-3 py-3.5 px-4">
                  <View className="w-8 items-center">
                    <MaterialIcons name="warning" size={20} color="#737373" />
                  </View>
                  <View className="flex-1">
                    <Text className="text-sm font-medium text-neutral-800 dark:text-neutral-100">
                      Low quota alert
                    </Text>
                    <Text className="text-xs text-neutral-400 mt-0.5">
                      Alert when weekly quota runs low
                    </Text>
                  </View>
                  <Switch
                    value={notif.settings.thresholdEnabled}
                    onValueChange={(v) => void notif.update({ thresholdEnabled: v })}
                    trackColor={{ false: COLORS.disabled, true: COLORS.claude }}
                    thumbColor="white"
                  />
                </View>

                {notif.settings.thresholdEnabled && (
                  <>
                    <Divider />
                    <View className="flex-row items-center gap-x-3 py-3 px-4">
                      <View className="w-8 items-center">
                        <MaterialIcons name="battery-alert" size={20} color="#737373" />
                      </View>
                      <Text className="flex-1 text-sm font-medium text-neutral-800 dark:text-neutral-100">
                        Alert below
                      </Text>
                      <View className="flex-row items-center gap-x-1">
                        <TextInput
                          value={thresholdInput}
                          onChangeText={setThresholdInput}
                          onBlur={handleThresholdBlur}
                          keyboardType="numeric"
                          returnKeyType="done"
                          maxLength={2}
                          className="text-sm font-mono text-neutral-600 dark:text-neutral-300 text-right"
                          style={{ minWidth: 28 }}
                        />
                        <Text className="text-sm text-neutral-400 dark:text-neutral-500">
                          % remaining
                        </Text>
                      </View>
                    </View>
                  </>
                )}
              </>
            )}
          </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>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

export default function SettingsTab() {
  return (
    <ScreenErrorBoundary screenName="Settings">
      <SettingsTabContent />
    </ScreenErrorBoundary>
  );
}
