import React from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
} from "react-native";
import { useQuery } from "@tanstack/react-query";
import { Feather } from "@expo/vector-icons";
import { router } from "expo-router";
import { useAuth } from "@clerk/clerk-expo";
import { customFetch } from "@workspace/api-client-react";
import { useColors } from "@/hooks/useColors";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import EmptyState from "@/components/EmptyState";

interface QuoteItem {
  quote: {
    id: number;
    subject: string;
    message: string;
    status: string;
    vendorResponse?: string;
    createdAt: string;
  };
  vendor: {
    id: number;
    companyName: string;
    city: string;
    logoUrl?: string;
  };
}

const STATUS_COLOR: Record<string, string> = {
  pending: "#F59E0B",
  responded: "#10B981",
  closed: "#6B7685",
};

export default function QuotesScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { isSignedIn, isLoaded } = useAuth();
  const isWeb = Platform.OS === "web";
  const topPad = isWeb ? 67 : insets.top;

  const { data = [], isLoading } = useQuery<QuoteItem[]>({
    queryKey: ["my-quotes"],
    queryFn: () => customFetch<QuoteItem[]>("/api/quote-requests/sent"),
    enabled: isSignedIn === true,
    retry: false,
  });

  if (!isLoaded) {
    return (
      <View style={[styles.center, { backgroundColor: colors.background }]}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <View
        style={[
          styles.header,
          {
            paddingTop: topPad + 16,
            backgroundColor: colors.background,
            borderBottomColor: colors.border,
          },
        ]}
      >
        <Text
          style={[
            styles.title,
            { color: colors.foreground, fontFamily: "Inter_700Bold" },
          ]}
        >
          My Quotes
        </Text>
      </View>

      {!isSignedIn ? (
        <View style={styles.center}>
          <View
            style={[
              styles.iconCircle,
              { backgroundColor: colors.muted, borderRadius: 40 },
            ]}
          >
            <Feather name="file-text" size={36} color={colors.mutedForeground} />
          </View>
          <Text
            style={[
              styles.gateTitle,
              { color: colors.foreground, fontFamily: "Inter_600SemiBold" },
            ]}
          >
            Sign in to view your quotes
          </Text>
          <Text
            style={[
              styles.gateSub,
              { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
            ]}
          >
            Track the status of your quote requests and vendor responses
          </Text>
          <TouchableOpacity
            onPress={() => router.push("/sign-in")}
            style={[
              styles.signInBtn,
              { backgroundColor: colors.primary, borderRadius: colors.radius },
            ]}
            activeOpacity={0.85}
          >
            <Text
              style={[
                styles.signInBtnText,
                { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
              ]}
            >
              Sign In
            </Text>
          </TouchableOpacity>
        </View>
      ) : isLoading ? (
        <View style={styles.center}>
          <ActivityIndicator color={colors.primary} size="large" />
        </View>
      ) : data.length === 0 ? (
        <EmptyState
          icon="file-text"
          title="No quote requests yet"
          subtitle="Browse products and vendors to send your first quote request"
        />
      ) : (
        <FlatList
          data={data}
          keyExtractor={(item) => item.quote.id.toString()}
          renderItem={({ item }) => {
            const statusColor =
              STATUS_COLOR[item.quote.status] ?? colors.mutedForeground;
            return (
              <View
                style={[
                  styles.card,
                  {
                    backgroundColor: colors.card,
                    borderColor: colors.border,
                    borderRadius: colors.radius,
                  },
                ]}
              >
                <View style={styles.cardRow}>
                  <View style={styles.cardBody}>
                    <Text
                      style={[
                        styles.subject,
                        { color: colors.foreground, fontFamily: "Inter_600SemiBold" },
                      ]}
                      numberOfLines={2}
                    >
                      {item.quote.subject}
                    </Text>
                    <Text
                      style={[
                        styles.vendorName,
                        { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
                      ]}
                    >
                      {item.vendor.companyName}
                    </Text>
                  </View>
                  <View
                    style={[
                      styles.statusPill,
                      {
                        backgroundColor: statusColor + "22",
                        borderRadius: 12,
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.statusText,
                        { color: statusColor, fontFamily: "Inter_500Medium" },
                      ]}
                    >
                      {item.quote.status}
                    </Text>
                  </View>
                </View>

                {item.quote.vendorResponse ? (
                  <View
                    style={[
                      styles.responseBox,
                      {
                        backgroundColor: colors.muted,
                        borderRadius: colors.radius - 2,
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.responseLabel,
                        { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
                      ]}
                    >
                      Vendor response
                    </Text>
                    <Text
                      style={[
                        styles.responseText,
                        { color: colors.foreground, fontFamily: "Inter_400Regular" },
                      ]}
                    >
                      {item.quote.vendorResponse}
                    </Text>
                  </View>
                ) : null}

                <Text
                  style={[
                    styles.dateText,
                    { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
                  ]}
                >
                  {new Date(item.quote.createdAt).toLocaleDateString("en-US", {
                    month: "short",
                    day: "numeric",
                    year: "numeric",
                  })}
                </Text>
              </View>
            );
          }}
          contentContainerStyle={{
            padding: 16,
            gap: 12,
            paddingBottom: isWeb ? 50 : 100,
          }}
          showsVerticalScrollIndicator={false}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    paddingHorizontal: 16,
    paddingBottom: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  title: { fontSize: 28 },
  center: { flex: 1, alignItems: "center", justifyContent: "center", padding: 32 },
  iconCircle: { width: 80, height: 80, alignItems: "center", justifyContent: "center" },
  gateTitle: { fontSize: 22, marginTop: 20, textAlign: "center" },
  gateSub: { fontSize: 15, marginTop: 10, textAlign: "center", lineHeight: 22 },
  signInBtn: {
    marginTop: 28,
    paddingHorizontal: 40,
    paddingVertical: 14,
  },
  signInBtnText: { fontSize: 16 },
  card: { padding: 16, borderWidth: StyleSheet.hairlineWidth },
  cardRow: { flexDirection: "row", gap: 12, alignItems: "flex-start" },
  cardBody: { flex: 1 },
  subject: { fontSize: 15, lineHeight: 20 },
  vendorName: { fontSize: 13, marginTop: 3 },
  statusPill: { paddingHorizontal: 10, paddingVertical: 4 },
  statusText: { fontSize: 12, textTransform: "capitalize" },
  responseBox: { marginTop: 12, padding: 12 },
  responseLabel: { fontSize: 12, marginBottom: 4 },
  responseText: { fontSize: 14, lineHeight: 20 },
  dateText: { fontSize: 12, marginTop: 10 },
});
