import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  ActivityIndicator,
  Alert,
  Platform,
} from "react-native";
import { Stack, useRouter, useLocalSearchParams } from "expo-router";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Plus, Ticket, ChevronRight } from "lucide-react-native";
import Colors from "@/constants/colors";
import { trpc } from "@/lib/trpc";
import { AppSiteFooter } from "@/components/AppSiteFooter";
import { useAuth } from "@/lib/auth-context";

const CATEGORIES = [
  "account",
  "transaction",
  "verification",
  "fraud",
  "technical",
  "billing",
  "other",
] as const;

export default function SupportTicketsScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const params = useLocalSearchParams<{ new?: string }>();
  const { isDemoMode } = useAuth();

  const [showCreate, setShowCreate] = useState(params.new === "1");
  const [subject, setSubject] = useState("");
  const [description, setDescription] = useState("");
  const [category, setCategory] = useState<(typeof CATEGORIES)[number]>("other");

  const ticketsQuery = trpc.support.getTickets.useQuery(undefined, { enabled: !isDemoMode });
  const createMutation = trpc.support.createTicket.useMutation({
    onSuccess: (data) => {
      setShowCreate(false);
      setSubject("");
      setDescription("");
      ticketsQuery.refetch();
      Alert.alert("Ticket Created", `Your ticket #${data.ticketNumber} was submitted. Zendo will respond within 7 business days.`);
    },
    onError: (e) => Alert.alert("Error", e.message),
  });

  const tickets = ticketsQuery.data?.tickets ?? [];

  const handleCreate = () => {
    if (subject.trim().length < 3 || description.trim().length < 10) {
      Alert.alert("Missing info", "Enter a subject and description (at least 10 characters).");
      return;
    }
    createMutation.mutate({
      category,
      subject: subject.trim(),
      description: description.trim(),
    });
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ title: "Support Tickets", headerShown: true, headerStyle: { backgroundColor: Colors.dark.background }, headerTintColor: Colors.dark.text }} />

      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator
        nestedScrollEnabled
      >
        <Text style={styles.lead}>
          File a support ticket and receive a ticket number. Zendo responds within up to 7 business days. Disputes follow the same timeline.
        </Text>

        <TouchableOpacity style={styles.newBtn} onPress={() => setShowCreate(!showCreate)}>
          <Plus size={18} color={Colors.dark.background} />
          <Text style={styles.newBtnText}>{showCreate ? "Cancel" : "New Support Ticket"}</Text>
        </TouchableOpacity>

        {showCreate ? (
          <View style={styles.form}>
            <Text style={styles.label}>Category</Text>
            <ScrollView horizontal showsHorizontalScrollIndicator nestedScrollEnabled contentContainerStyle={styles.catRow}>
              {CATEGORIES.map((c) => (
                <TouchableOpacity
                  key={c}
                  style={[styles.catChip, category === c && styles.catChipActive]}
                  onPress={() => setCategory(c)}
                >
                  <Text style={[styles.catChipText, category === c && styles.catChipTextActive]}>{c}</Text>
                </TouchableOpacity>
              ))}
            </ScrollView>
            <Text style={styles.label}>Subject</Text>
            <TextInput style={styles.input} value={subject} onChangeText={setSubject} placeholder="Brief summary" placeholderTextColor={Colors.dark.textTertiary} />
            <Text style={styles.label}>Description</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              value={description}
              onChangeText={setDescription}
              placeholder="Describe your issue in detail..."
              placeholderTextColor={Colors.dark.textTertiary}
              multiline
              numberOfLines={5}
            />
            <TouchableOpacity style={styles.submitBtn} onPress={handleCreate} disabled={createMutation.isPending}>
              {createMutation.isPending ? <ActivityIndicator color={Colors.dark.background} /> : <Text style={styles.submitText}>Submit Ticket</Text>}
            </TouchableOpacity>
          </View>
        ) : null}

        {isDemoMode ? (
          <Text style={styles.demoNote}>Sign in with a real account to create and manage support tickets.</Text>
        ) : ticketsQuery.isLoading ? (
          <ActivityIndicator color={Colors.dark.primary} style={{ marginTop: 24 }} />
        ) : tickets.length === 0 ? (
          <View style={styles.empty}>
            <Ticket size={40} color={Colors.dark.textTertiary} />
            <Text style={styles.emptyText}>No tickets yet</Text>
          </View>
        ) : (
          tickets.map((t) => (
            <TouchableOpacity
              key={t.id}
              style={styles.ticketCard}
              onPress={() => router.push(`/support-ticket/${t.id}` as never)}
            >
              <View style={{ flex: 1 }}>
                <Text style={styles.ticketNum}>#{t.ticketNumber}</Text>
                <Text style={styles.ticketSubject}>{t.subject}</Text>
                <Text style={styles.ticketMeta}>{t.status.replace(/_/g, " ")} · {t.category}</Text>
              </View>
              <ChevronRight size={18} color={Colors.dark.textTertiary} />
            </TouchableOpacity>
          ))
        )}

        <AppSiteFooter />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.dark.background },
  scroll: { flex: 1 },
  scrollContent: { padding: 20, paddingBottom: 40 },
  lead: { color: Colors.dark.textSecondary, fontSize: 14, lineHeight: 20, marginBottom: 16 },
  newBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 8, backgroundColor: Colors.dark.primary, padding: 14, borderRadius: 12, marginBottom: 16 },
  newBtnText: { color: Colors.dark.background, fontWeight: "700", fontSize: 15 },
  form: { backgroundColor: Colors.dark.surface, borderRadius: 14, padding: 16, marginBottom: 20, borderWidth: 1, borderColor: Colors.dark.border },
  label: { color: Colors.dark.text, fontWeight: "600", marginBottom: 8, marginTop: 8 },
  input: { backgroundColor: Colors.dark.background, borderWidth: 1, borderColor: Colors.dark.border, borderRadius: 10, padding: 12, color: Colors.dark.text, marginBottom: 8, ...Platform.select({ web: { outlineStyle: "none" as const } }) },
  textArea: { minHeight: 100, textAlignVertical: "top" },
  catRow: { gap: 8, paddingBottom: 8 },
  catChip: { paddingHorizontal: 12, paddingVertical: 8, borderRadius: 20, backgroundColor: Colors.dark.background, borderWidth: 1, borderColor: Colors.dark.border },
  catChipActive: { borderColor: Colors.dark.primary, backgroundColor: Colors.dark.surfaceElevated },
  catChipText: { color: Colors.dark.textSecondary, fontSize: 12, textTransform: "capitalize" },
  catChipTextActive: { color: Colors.dark.primary, fontWeight: "700" },
  submitBtn: { backgroundColor: Colors.dark.primary, padding: 14, borderRadius: 10, alignItems: "center", marginTop: 8 },
  submitText: { color: Colors.dark.background, fontWeight: "700" },
  demoNote: { color: Colors.dark.textTertiary, textAlign: "center", marginTop: 24 },
  empty: { alignItems: "center", padding: 40, gap: 8 },
  emptyText: { color: Colors.dark.textSecondary },
  ticketCard: { flexDirection: "row", alignItems: "center", backgroundColor: Colors.dark.surface, borderRadius: 12, padding: 16, marginBottom: 10, borderWidth: 1, borderColor: Colors.dark.border },
  ticketNum: { color: Colors.dark.primary, fontWeight: "700", fontSize: 13 },
  ticketSubject: { color: Colors.dark.text, fontWeight: "600", marginTop: 4 },
  ticketMeta: { color: Colors.dark.textTertiary, fontSize: 12, marginTop: 4, textTransform: "capitalize" },
});
