/**
 * Settings screen for Scry app.
 */

import React, { useState } from "react";
import {
  StyleSheet,
  View,
  Text,
  ScrollView,
  Pressable,
  Switch,
  ActivityIndicator,
  Alert,
} from "react-native";
import { FontAwesome } from "@expo/vector-icons";
import { useQuery } from "convex/react";
import { api } from "../../convex/_generated/api";
import { useSync } from "@/lib/hooks/useSync";
import { useHashCache } from "@/lib/context";

interface SettingRowProps {
  icon: React.ComponentProps<typeof FontAwesome>["name"];
  title: string;
  subtitle?: string;
  onPress?: () => void;
  rightElement?: React.ReactNode;
  destructive?: boolean;
}

function SettingRow({
  icon,
  title,
  subtitle,
  onPress,
  rightElement,
  destructive,
}: SettingRowProps) {
  return (
    <Pressable
      style={({ pressed }) => [
        styles.settingRow,
        pressed && onPress && styles.settingRowPressed,
      ]}
      onPress={onPress}
      disabled={!onPress}
    >
      <View style={[styles.settingIcon, destructive && styles.settingIconDestructive]}>
        <FontAwesome name={icon} size={18} color={destructive ? "#FF6B6B" : "#007AFF"} />
      </View>
      <View style={styles.settingContent}>
        <Text style={[styles.settingTitle, destructive && styles.settingTitleDestructive]}>
          {title}
        </Text>
        {subtitle && <Text style={styles.settingSubtitle}>{subtitle}</Text>}
      </View>
      {rightElement || (onPress && <FontAwesome name="chevron-right" size={14} color="#666" />)}
    </Pressable>
  );
}

function SettingSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>{title}</Text>
      <View style={styles.sectionContent}>{children}</View>
    </View>
  );
}

export default function SettingsScreen() {
  const [cardDetectionEnabled, setCardDetectionEnabled] = useState(true);
  const [rotationMatchingEnabled, setRotationMatchingEnabled] = useState(true);

  // Get hash count from context
  const { cardHashes, hashesLoaded } = useHashCache();

  // Sync hook for cache management
  const { isInitialized, isSyncing, lastSync, localCardCount, error: syncError, sync, clearCache } =
    useSync();

  // Get total card count from Convex
  const cardCount = useQuery(api.cards.count);

  const formatLastSync = (timestamp: number) => {
    if (!timestamp) return "Never";
    const date = new Date(timestamp);
    return date.toLocaleDateString() + " " + date.toLocaleTimeString();
  };

  const handleClearCache = () => {
    Alert.alert(
      "Clear Local Cache",
      "This will remove all downloaded card data. You'll need to sync again to scan cards.",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Clear",
          style: "destructive",
          onPress: async () => {
            await clearCache();
            Alert.alert("Cache Cleared", "Local card data has been removed.");
          },
        },
      ]
    );
  };

  const handleManualSync = async () => {
    await sync();
    Alert.alert("Sync Complete", `${localCardCount} cards now available for scanning.`);
  };

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      {/* Database section */}
      <SettingSection title="Database">
        <SettingRow
          icon="database"
          title="Card Database"
          subtitle={
            isInitialized
              ? `${localCardCount.toLocaleString()} cards cached locally`
              : isSyncing
                ? "Loading..."
                : "Not initialized"
          }
          rightElement={isSyncing ? <ActivityIndicator size="small" color="#007AFF" /> : undefined}
        />
        <SettingRow
          icon="refresh"
          title="Sync Now"
          subtitle={`Last sync: ${formatLastSync(lastSync)}`}
          onPress={handleManualSync}
          rightElement={isSyncing ? <ActivityIndicator size="small" color="#007AFF" /> : undefined}
        />
        {syncError && (
          <SettingRow icon="exclamation-triangle" title="Sync Error" subtitle={syncError} destructive />
        )}
      </SettingSection>

      {/* Recognition section */}
      <SettingSection title="Recognition">
        <SettingRow
          icon="crop"
          title="Card Detection"
          subtitle="Automatically detect card boundaries"
          rightElement={
            <Switch
              value={cardDetectionEnabled}
              onValueChange={setCardDetectionEnabled}
              trackColor={{ true: "#007AFF" }}
            />
          }
        />
        <SettingRow
          icon="rotate-right"
          title="Rotation Matching"
          subtitle="Try multiple rotations for matching"
          rightElement={
            <Switch
              value={rotationMatchingEnabled}
              onValueChange={setRotationMatchingEnabled}
              trackColor={{ true: "#007AFF" }}
            />
          }
        />
      </SettingSection>

      {/* Collection section */}
      <SettingSection title="Collection">
        <SettingRow
          icon="th-large"
          title="Cards in Database"
          subtitle={`${(cardCount ?? 0).toLocaleString()} cards available`}
        />
        <SettingRow
          icon="cloud-upload"
          title="Export Collection"
          subtitle="Export as CSV or JSON"
          onPress={() => {
            // TODO: Implement export
          }}
        />
      </SettingSection>

      {/* About section */}
      <SettingSection title="About">
        <SettingRow icon="info-circle" title="Version" subtitle="1.0.0 (Expo + Convex)" />
        <SettingRow
          icon="github"
          title="Source Code"
          subtitle="View on Forgejo"
          onPress={() => {
            // TODO: Open source URL
          }}
        />
      </SettingSection>

      {/* Danger zone */}
      <SettingSection title="Danger Zone">
        <SettingRow
          icon="trash"
          title="Clear Collection"
          subtitle="Remove all cards from collection"
          onPress={() => {
            Alert.alert(
              "Clear Collection",
              "This will remove all cards from your collection. This cannot be undone.",
              [
                { text: "Cancel", style: "cancel" },
                { text: "Clear", style: "destructive", onPress: () => {} },
              ]
            );
          }}
          destructive
        />
        <SettingRow
          icon="eraser"
          title="Clear Local Cache"
          subtitle="Remove downloaded card data"
          onPress={handleClearCache}
          destructive
        />
      </SettingSection>

      {/* Footer */}
      <View style={styles.footer}>
        <Text style={styles.footerText}>Scry • Card scanner for Magic: The Gathering</Text>
        <Text style={styles.footerSubtext}>Card data © Wizards of the Coast</Text>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#1a1a1a",
  },
  content: {
    paddingBottom: 40,
  },
  section: {
    marginTop: 24,
  },
  sectionTitle: {
    color: "#888",
    fontSize: 13,
    fontWeight: "600",
    textTransform: "uppercase",
    letterSpacing: 0.5,
    marginLeft: 16,
    marginBottom: 8,
  },
  sectionContent: {
    backgroundColor: "#2a2a2a",
    borderRadius: 12,
    marginHorizontal: 16,
    overflow: "hidden",
  },
  settingRow: {
    flexDirection: "row",
    alignItems: "center",
    padding: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: "#3a3a3a",
  },
  settingRowPressed: {
    backgroundColor: "#333",
  },
  settingIcon: {
    width: 32,
    height: 32,
    borderRadius: 8,
    backgroundColor: "rgba(0,122,255,0.1)",
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  settingIconDestructive: {
    backgroundColor: "rgba(255,107,107,0.1)",
  },
  settingContent: {
    flex: 1,
  },
  settingTitle: {
    color: "#fff",
    fontSize: 16,
  },
  settingTitleDestructive: {
    color: "#FF6B6B",
  },
  settingSubtitle: {
    color: "#888",
    fontSize: 13,
    marginTop: 2,
  },
  footer: {
    marginTop: 40,
    alignItems: "center",
    paddingHorizontal: 16,
  },
  footerText: {
    color: "#666",
    fontSize: 14,
  },
  footerSubtext: {
    color: "#444",
    fontSize: 12,
    marginTop: 4,
  },
});
