import {
  ScrollView,
  View,
  Text,
  TouchableOpacity,
  ActivityIndicator,
  RefreshControl,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { MaterialIcons } from "@expo/vector-icons";
import { useCodexUsage } from "@/hooks/useCodexUsage";
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";
import { windowLabel } from "@/lib/timeUtils";
import type { CodexResetCredit } from "@/types/codex";

function formatResetStatus(status?: string) {
  if (!status) return "Unknown";
  return status.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
}

function ResetCreditRow({ credit }: { credit: CodexResetCredit }) {
  return (
    <View className="mt-2 rounded-xl bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-700 p-3">
      <View className="flex-row items-center justify-between mb-1.5">
        <Text className="text-sm font-semibold text-neutral-900 dark:text-white">
          Credit {credit.index}
        </Text>
        <View className="px-2 py-0.5 rounded-full bg-green-100 dark:bg-green-900/30">
          <Text className="text-[11px] font-semibold text-green-700 dark:text-green-300">
            {formatResetStatus(credit.status)}
          </Text>
        </View>
      </View>
      {credit.timeUntilExpiry && (
        <Text className="text-sm text-neutral-700 dark:text-neutral-300">
          Expires in {credit.timeUntilExpiry}
        </Text>
      )}
      {credit.expiresAtLocal && (
        <Text className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">
          Expires {credit.expiresAtLocal}
        </Text>
      )}
      {credit.grantedAtLocal && (
        <Text className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">
          Granted {credit.grantedAtLocal}
        </Text>
      )}
    </View>
  );
}

function CodexTabContent() {
  const {
    auth,
    usage,
    lastFetchedAt,
    status,
    error,
    importAuthFile,
    refresh,
    clearAuth,
  } =
    useCodexUsage();
  const resetCoupons = usage?.resetCoupons;
  const availableResetCredits =
    resetCoupons?.credits?.filter((credit) => credit.status === "available") ?? [];

  return (
    <SafeAreaView
      className="flex-1 bg-neutral-50 dark:bg-neutral-950"
      edges={["top", "bottom"]}
    >
      <ScrollView
        className="flex-1"
        contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32 }}
        refreshControl={
          <RefreshControl
            refreshing={status === "loading"}
            onRefresh={refresh}
            tintColor={COLORS.codex}
          />
        }
      >
        {/* 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.codex}22` }}
          >
            <MaterialIcons name="auto-awesome" size={18} color={COLORS.codex} />
          </View>
          <View>
            <Text className="text-xl font-bold text-neutral-900 dark:text-white tracking-tight">
              Codex CLI
            </Text>
            <Text className="text-xs text-neutral-400 mt-0.5">
              Rate limits & credits
            </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" ? 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>
                {auth.accountId && (
                  <Text className="text-xs text-neutral-400 dark:text-neutral-500 font-mono">
                    {auth.accountId.slice(0, 10)}…
                  </Text>
                )}
              </View>
              <TouchableOpacity
                onPress={clearAuth}
                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>
              <TouchableOpacity
                onPress={importAuthFile}
                className="flex-row items-center justify-center gap-x-2 py-3.5 px-4 rounded-xl"
                style={{ backgroundColor: COLORS.codex }}
              >
                <MaterialIcons name="upload-file" size={16} color="white" />
                <Text className="text-white font-semibold text-sm">
                  Import auth.json
                </Text>
              </TouchableOpacity>
              <Text className="text-xs text-neutral-400 text-center mt-2">
                Located at ~/.codex/auth.json
              </Text>
            </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">
                Import auth.json to see your rate limits
              </Text>
            </View>
          )}
          {status === "loading" && !usage && (
            <ActivityIndicator color={COLORS.codex} style={{ marginVertical: 24 }} />
          )}
          {status === "error" && error && <ErrorMessage message={error} />}
          {usage && (
            <View>
              {/* Plan badge */}
              <View className="flex-row items-center mb-5">
                <View className="px-2.5 py-1 rounded-full bg-green-100 dark:bg-green-900/40">
                  <Text className="text-xs font-semibold text-green-700 dark:text-green-300 capitalize">
                    {usage.planType ?? "codex"}
                  </Text>
                </View>
              </View>

              {usage.primary && (
                <UsageStat
                  label={`Primary (${windowLabel(usage.primary.windowSeconds)})`}
                  percent={usage.primary.usedPercent}
                  resetAtSeconds={usage.primary.resetsAt}
                />
              )}
              {usage.secondary && (
                <UsageStat
                  label={`Secondary (${windowLabel(usage.secondary.windowSeconds)})`}
                  percent={usage.secondary.usedPercent}
                  resetAtSeconds={usage.secondary.resetsAt}
                />
              )}

              {/* Credits */}
              <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-2">
                  Credits
                </Text>
                {usage.credits.unlimited ? (
                  <View className="flex-row items-center gap-x-2">
                    <MaterialIcons name="all-inclusive" size={16} color={COLORS.codex} />
                    <Text className="text-sm font-semibold text-green-600 dark:text-green-400">
                      Unlimited
                    </Text>
                  </View>
                ) : usage.credits.hasCredits ? (
                  <Text className="text-sm font-semibold text-neutral-900 dark:text-white">
                    ${Number(usage.credits.balance).toFixed(2)} remaining
                  </Text>
                ) : (
                  <Text className="text-sm text-neutral-400">No credits</Text>
                )}
              </View>

              {resetCoupons && (
                <View className="mt-3 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-2">
                    Reset Credits
                  </Text>
                  <Text className="text-sm font-semibold text-neutral-900 dark:text-white">
                    {resetCoupons.availableCount ?? 0} available
                  </Text>
                  {typeof resetCoupons.totalEarnedCount === "number" && (
                    <Text className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">
                      {resetCoupons.totalEarnedCount} earned total
                    </Text>
                  )}
                  {resetCoupons.nextExpiringCredit?.expiresAtLocal && (
                    <Text className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">
                      Next expires {resetCoupons.nextExpiringCredit.expiresAtLocal}
                    </Text>
                  )}
                  {resetCoupons.nextExpiringCredit?.timeUntilExpiry && (
                    <Text className="text-xs text-neutral-400 dark:text-neutral-500 mt-0.5">
                      In {resetCoupons.nextExpiringCredit.timeUntilExpiry}
                    </Text>
                  )}
                  {availableResetCredits.length > 0 && (
                    <View className="mt-3 pt-3 border-t border-neutral-200 dark:border-neutral-700">
                      <Text className="text-xs font-semibold uppercase tracking-widest text-neutral-400 mb-1">
                        Available Now
                      </Text>
                      {availableResetCredits.map((credit) => (
                        <ResetCreditRow key={`${credit.index}-${credit.expiresAt ?? "none"}`} credit={credit} />
                      ))}
                    </View>
                  )}
                  {resetCoupons.source !== "live_api" && (
                    <Text className="text-xs text-neutral-400 dark:text-neutral-500 mt-3">
                      Source: {resetCoupons.sourceDescription}
                    </Text>
                  )}
                </View>
              )}
              <View className="mt-4 border-t border-neutral-100 pt-3 dark:border-neutral-800">
                <LastUpdated timestamp={lastFetchedAt} />
              </View>
            </View>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

export default function CodexTab() {
  return (
    <ScreenErrorBoundary screenName="Codex">
      <CodexTabContent />
    </ScreenErrorBoundary>
  );
}
