import {
  ScrollView,
  View,
  Text,
  TouchableOpacity,
  TextInput,
  ActivityIndicator,
  RefreshControl,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { MaterialIcons } from "@expo/vector-icons";
import { useClaudeUsage } from "@/hooks/useClaudeUsage";
import { UsageStat } from "@/components/UsageStat";
import { ErrorMessage } from "@/components/ErrorMessage";
import { LastUpdated } from "@/components/LastUpdated";
import { ScreenErrorBoundary } from "@/components/ScreenErrorBoundary";
import { COLORS } from "@/lib/constants";

function ClaudeTabContent() {
  const {
    auth,
    pendingKey,
    setPendingKey,
    pendingOrg,
    setPendingOrg,
    usage,
    lastFetchedAt,
    status,
    error,
    keyValidationError,
    canSaveKey,
    saveKey,
    refresh,
    clearKey,
  } = useClaudeUsage();

  return (
    <SafeAreaView
      className="flex-1 bg-neutral-50 dark:bg-neutral-950"
      edges={["top", "bottom"]}
    >
      <KeyboardAvoidingView
        className="flex-1"
        behavior={Platform.OS === "ios" ? "padding" : "height"}
      >
        <ScrollView
          className="flex-1"
          contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32 }}
          keyboardShouldPersistTaps="handled"
          refreshControl={
            <RefreshControl
              refreshing={status === "loading"}
              onRefresh={refresh}
              tintColor={COLORS.claude}
            />
          }
        >
          {/* Header */}
          <View className="flex-row items-center gap-x-3 py-5">
            <View
              className="w-9 h-9 rounded-xl items-center justify-center"
              style={{ backgroundColor: `${COLORS.claude}22` }}
            >
              <MaterialIcons name="psychology" size={18} color={COLORS.claude} />
            </View>
            <View>
              <Text className="text-xl font-bold text-neutral-900 dark:text-white tracking-tight">
                Claude.ai
              </Text>
              <Text className="text-xs text-neutral-400 mt-0.5">
                Usage windows
              </Text>
            </View>
          </View>

          {/* Configuration card */}
          <View className="bg-white dark:bg-neutral-900 rounded-2xl border border-neutral-200 dark:border-neutral-800 p-4 mb-4">
            <Text className="text-xs font-semibold uppercase tracking-widest text-neutral-400 dark:text-neutral-500 mb-3">
              Configuration
            </Text>
            <ErrorMessage
              message={error && (status === "idle" || status === "error") ? error : null}
            />
            {auth ? (
              <View className="flex-row items-center justify-between">
                <View className="flex-row items-center gap-x-2.5">
                  <View className="w-2 h-2 rounded-full bg-green-500" />
                  <Text className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
                    Connected
                  </Text>
                  <Text className="text-xs text-neutral-400 dark:text-neutral-500 font-mono">
                    {auth.sessionKey.slice(0, 10)}…
                  </Text>
                </View>
                <TouchableOpacity
                  onPress={clearKey}
                  className="px-3 py-1.5 rounded-lg bg-neutral-100 dark:bg-neutral-800"
                >
                  <Text className="text-xs font-medium text-neutral-500 dark:text-neutral-400">
                    Clear
                  </Text>
                </TouchableOpacity>
              </View>
            ) : (
              <View>
                <TextInput
                  value={pendingKey}
                  onChangeText={setPendingKey}
                  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-white dark:bg-neutral-800 mb-2"
                />
                {keyValidationError && (
                  <Text selectable className="mb-2 text-xs text-red-500">
                    {keyValidationError}
                  </Text>
                )}
                <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-white dark:bg-neutral-800 mb-3"
                />
                <TouchableOpacity
                  onPress={saveKey}
                  disabled={!canSaveKey}
                  className="py-3.5 px-4 rounded-xl items-center"
                  style={{
                    backgroundColor: canSaveKey ? COLORS.claude : COLORS.disabled,
                  }}
                >
                  <Text
                    className="font-semibold text-sm"
                    style={{ color: canSaveKey ? "white" : COLORS.muted }}
                  >
                    Save Session Key
                  </Text>
                </TouchableOpacity>
                <View className="bg-neutral-50 dark:bg-neutral-800 rounded-xl p-3.5 mt-3 border border-neutral-100 dark:border-neutral-700">
                  <Text className="text-xs font-semibold text-neutral-400 uppercase tracking-widest mb-1.5">
                    Where to find it
                  </Text>
                  <Text className="text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed">
                    Chrome DevTools → Application → Cookies → claude.ai → copy{" "}
                    <Text className="font-mono text-neutral-600 dark:text-neutral-300">sessionKey</Text>
                    {" "}and optionally{" "}
                    <Text className="font-mono text-neutral-600 dark:text-neutral-300">lastActiveOrg</Text>
                  </Text>
                </View>
              </View>
            )}
          </View>

          {/* Usage card */}
          <View className="bg-white dark:bg-neutral-900 rounded-2xl border border-neutral-200 dark:border-neutral-800 p-4">
            <Text className="text-xs font-semibold uppercase tracking-widest text-neutral-400 dark:text-neutral-500 mb-3">
              Usage
            </Text>

            {status === "idle" && !auth && (
              <View className="items-center py-8">
                <MaterialIcons name="insert-chart-outlined" size={32} color="#d4d4d4" />
                <Text className="text-sm text-neutral-400 text-center mt-3">
                  Enter your session key to see usage windows
                </Text>
              </View>
            )}
            {status === "loading" && !usage && (
              <ActivityIndicator color={COLORS.claude} style={{ marginVertical: 24 }} />
            )}
            {status === "error" && error && <ErrorMessage message={error} />}
            {usage && (
              <View>
                <UsageStat
                  label="5-hour window"
                  percent={usage.five_hour.utilization}
                  resetAtISO={usage.five_hour.resets_at}
                />
                <UsageStat
                  label="7-day window"
                  percent={usage.seven_day.utilization}
                  resetAtISO={usage.seven_day.resets_at}
                />

                {(usage.seven_day_sonnet || usage.seven_day_opus) && (
                  <View className="mt-1 p-3.5 rounded-xl bg-neutral-50 dark:bg-neutral-800 border border-neutral-100 dark:border-neutral-700">
                    <Text className="text-xs font-semibold uppercase tracking-widest text-neutral-400 mb-3">
                      By Model (7-day)
                    </Text>
                    {usage.seven_day_sonnet && (
                      <UsageStat
                        label="Sonnet"
                        percent={usage.seven_day_sonnet.utilization}
                      />
                    )}
                    {usage.seven_day_opus && (
                      <UsageStat
                        label="Opus"
                        percent={usage.seven_day_opus.utilization}
                      />
                    )}
                  </View>
                )}
                <View className="mt-4 border-t border-neutral-100 pt-3 dark:border-neutral-800">
                  <LastUpdated timestamp={lastFetchedAt} />
                </View>
              </View>
            )}
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

export default function ClaudeTab() {
  return (
    <ScreenErrorBoundary screenName="Claude">
      <ClaudeTabContent />
    </ScreenErrorBoundary>
  );
}
