import React, { useState, useCallback } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Linking,
  RefreshControl,
  Platform,
} from "react-native";
import { useLocalSearchParams, router, Stack } from "expo-router";
import { useQuery } from "@tanstack/react-query";
import { Feather } from "@expo/vector-icons";
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 StarRating from "@/components/StarRating";
import QuoteModal from "@/components/QuoteModal";

interface VendorProduct {
  id: number;
  name: string;
  nameAr?: string;
  category: string;
  minPrice?: string;
  maxPrice?: string;
  currency: string;
  unit: string;
  inStock: boolean;
  imageUrl?: string;
}

interface VendorDetail {
  id: number;
  companyName: string;
  companyNameAr?: string;
  sector: string;
  city: string;
  description?: string;
  phone?: string;
  contactEmail: string;
  website?: string;
  logoUrl?: string;
  isVerified: boolean;
  rating: string;
  totalReviews: number;
  products: VendorProduct[];
}

export default function VendorDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { isSignedIn } = useAuth();
  const isWeb = Platform.OS === "web";

  const [showQuoteModal, setShowQuoteModal] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const { data: vendor, isLoading, refetch } = useQuery<VendorDetail>({
    queryKey: ["vendor-detail", id],
    queryFn: () => customFetch<VendorDetail>(`/api/vendors/${id}`),
    enabled: !!id,
  });

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await refetch();
    setRefreshing(false);
  }, [refetch]);

  const handleRequestQuote = () => {
    if (!isSignedIn) {
      router.push("/sign-in");
      return;
    }
    setShowQuoteModal(true);
  };

  const groupedProducts =
    vendor?.products?.reduce(
      (acc, p) => {
        if (!acc[p.category]) acc[p.category] = [];
        acc[p.category].push(p);
        return acc;
      },
      {} as Record<string, VendorProduct[]>
    ) ?? {};

  const rating = parseFloat(vendor?.rating ?? "0") || 0;
  const bottomFabPad = isWeb ? 50 : insets.bottom + 16;

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

  if (!vendor) {
    return (
      <View style={[styles.center, { backgroundColor: colors.background }]}>
        <Feather name="alert-circle" size={48} color={colors.mutedForeground} />
        <Text style={[styles.notFoundText, { color: colors.foreground, fontFamily: "Inter_600SemiBold" }]}>
          Vendor not found
        </Text>
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Stack.Screen
        options={{
          title: vendor.companyName,
          headerBackTitle: "Back",
          headerStyle: { backgroundColor: colors.secondary },
          headerTintColor: "#ECF0F9",
          headerTitleStyle: { fontFamily: "Inter_600SemiBold", color: "#ECF0F9" },
        }}
      />

      <ScrollView
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={handleRefresh}
            tintColor={colors.primary}
          />
        }
        contentContainerStyle={{ paddingBottom: 120 }}
        showsVerticalScrollIndicator={false}
      >
        {/* Hero */}
        <View
          style={[
            styles.hero,
            { backgroundColor: colors.secondary },
          ]}
        >
          <View
            style={[
              styles.logoCircle,
              { backgroundColor: colors.primary + "28", borderRadius: 36 },
            ]}
          >
            <Text
              style={[
                styles.logoLetter,
                { color: colors.primary, fontFamily: "Inter_700Bold" },
              ]}
            >
              {vendor.companyName[0]}
            </Text>
          </View>

          <Text
            style={[
              styles.vendorName,
              { color: "#ECF0F9", fontFamily: "Inter_700Bold" },
            ]}
          >
            {vendor.companyName}
          </Text>

          <View style={styles.heroMeta}>
            <Feather name="map-pin" size={13} color="#8C96A8" />
            <Text
              style={[
                styles.heroCity,
                { color: "#8C96A8", fontFamily: "Inter_400Regular" },
              ]}
            >
              {" "}
              {vendor.city}
            </Text>
            {vendor.sector ? (
              <>
                <Text style={{ color: "#3D5275" }}> · </Text>
                <Text
                  style={[
                    styles.heroCity,
                    { color: "#8C96A8", fontFamily: "Inter_400Regular" },
                  ]}
                >
                  {vendor.sector}
                </Text>
              </>
            ) : null}
            {vendor.isVerified && (
              <>
                <Text style={{ color: "#3D5275" }}> · </Text>
                <Feather name="check-circle" size={13} color={colors.primary} />
                <Text
                  style={[
                    styles.heroCity,
                    { color: colors.primary, fontFamily: "Inter_500Medium" },
                  ]}
                >
                  {" "}
                  Verified
                </Text>
              </>
            )}
          </View>

          {rating > 0 && (
            <View style={styles.heroRating}>
              <StarRating value={rating} size={15} />
              <Text
                style={[
                  styles.ratingText,
                  { color: "#8C96A8", fontFamily: "Inter_400Regular" },
                ]}
              >
                {" "}
                {vendor.rating} ({vendor.totalReviews} reviews)
              </Text>
            </View>
          )}
        </View>

        {/* Contact */}
        {(vendor.phone || vendor.contactEmail) && (
          <View
            style={[
              styles.section,
              {
                backgroundColor: colors.card,
                borderTopColor: colors.border,
                borderBottomColor: colors.border,
              },
            ]}
          >
            {vendor.phone && (
              <TouchableOpacity
                style={styles.contactRow}
                onPress={() => Linking.openURL(`tel:${vendor.phone}`)}
                activeOpacity={0.7}
              >
                <Feather name="phone" size={16} color={colors.primary} />
                <Text
                  style={[
                    styles.contactText,
                    { color: colors.foreground, fontFamily: "Inter_400Regular" },
                  ]}
                >
                  {vendor.phone}
                </Text>
                <Feather name="chevron-right" size={16} color={colors.mutedForeground} />
              </TouchableOpacity>
            )}
            {vendor.contactEmail && (
              <TouchableOpacity
                style={[
                  styles.contactRow,
                  vendor.phone
                    ? { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.border }
                    : {},
                ]}
                onPress={() => Linking.openURL(`mailto:${vendor.contactEmail}`)}
                activeOpacity={0.7}
              >
                <Feather name="mail" size={16} color={colors.primary} />
                <Text
                  style={[
                    styles.contactText,
                    { color: colors.foreground, fontFamily: "Inter_400Regular" },
                  ]}
                >
                  {vendor.contactEmail}
                </Text>
                <Feather name="chevron-right" size={16} color={colors.mutedForeground} />
              </TouchableOpacity>
            )}
          </View>
        )}

        {/* Description */}
        {vendor.description ? (
          <View
            style={[
              styles.descBlock,
              { backgroundColor: colors.card, borderTopColor: colors.border, borderBottomColor: colors.border },
            ]}
          >
            <Text
              style={[
                styles.sectionHeading,
                { color: colors.mutedForeground, fontFamily: "Inter_600SemiBold" },
              ]}
            >
              About
            </Text>
            <Text
              style={[
                styles.descText,
                { color: colors.foreground, fontFamily: "Inter_400Regular" },
              ]}
            >
              {vendor.description}
            </Text>
          </View>
        ) : null}

        {/* Products by category */}
        {Object.entries(groupedProducts).length > 0 ? (
          Object.entries(groupedProducts).map(([category, prods]) => (
            <View key={category} style={{ marginTop: 12 }}>
              <Text
                style={[
                  styles.categoryHeading,
                  { color: colors.foreground, fontFamily: "Inter_700Bold" },
                ]}
              >
                {category}
              </Text>
              {prods.map((p) => (
                <View
                  key={p.id}
                  style={[
                    styles.productRow,
                    {
                      backgroundColor: colors.card,
                      borderColor: colors.border,
                      borderRadius: colors.radius,
                    },
                  ]}
                >
                  <View style={styles.productLeft}>
                    <View style={styles.productTopLine}>
                      <Text
                        style={[
                          styles.productName,
                          { color: colors.foreground, fontFamily: "Inter_600SemiBold" },
                        ]}
                        numberOfLines={2}
                      >
                        {p.name}
                      </Text>
                      {p.inStock && (
                        <View
                          style={[
                            styles.availableDot,
                            { backgroundColor: colors.primary + "22", borderRadius: 8 },
                          ]}
                        >
                          <Text
                            style={[
                              styles.availableText,
                              { color: colors.primary, fontFamily: "Inter_500Medium" },
                            ]}
                          >
                            In stock
                          </Text>
                        </View>
                      )}
                    </View>
                    {(p.minPrice || p.maxPrice) && (
                      <Text
                        style={[
                          styles.productPrice,
                          { color: colors.accent, fontFamily: "Inter_700Bold" },
                        ]}
                      >
                        {p.currency}{" "}
                        {p.minPrice}
                        {p.maxPrice && p.maxPrice !== p.minPrice
                          ? ` – ${p.maxPrice}`
                          : ""}
                        {" "}/ {p.unit}
                      </Text>
                    )}
                  </View>
                </View>
              ))}
            </View>
          ))
        ) : (
          <View style={{ paddingTop: 20 }}>
            <Text
              style={[
                styles.noProdText,
                { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
              ]}
            >
              No products listed yet
            </Text>
          </View>
        )}
      </ScrollView>

      {/* FAB */}
      <View style={[styles.fabWrap, { bottom: bottomFabPad }]}>
        <TouchableOpacity
          onPress={handleRequestQuote}
          activeOpacity={0.85}
          style={[
            styles.fab,
            {
              backgroundColor: colors.primary,
              borderRadius: colors.radius + 4,
            },
          ]}
        >
          <Feather name="send" size={18} color={colors.primaryForeground} />
          <Text
            style={[
              styles.fabLabel,
              { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
            ]}
          >
            Request Quote
          </Text>
        </TouchableOpacity>
      </View>

      <QuoteModal
        visible={showQuoteModal}
        vendorId={vendor.id}
        vendorName={vendor.companyName}
        onClose={() => setShowQuoteModal(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  center: { flex: 1, alignItems: "center", justifyContent: "center" },
  notFoundText: { fontSize: 18, marginTop: 16 },
  hero: {
    paddingHorizontal: 24,
    paddingTop: 28,
    paddingBottom: 28,
    alignItems: "center",
  },
  logoCircle: {
    width: 76,
    height: 76,
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 14,
  },
  logoLetter: { fontSize: 30 },
  vendorName: { fontSize: 22, textAlign: "center" },
  heroMeta: { flexDirection: "row", alignItems: "center", marginTop: 8, flexWrap: "wrap", justifyContent: "center" },
  heroCity: { fontSize: 14 },
  heroRating: { flexDirection: "row", alignItems: "center", marginTop: 10 },
  ratingText: { fontSize: 13 },
  section: {
    borderTopWidth: StyleSheet.hairlineWidth,
    borderBottomWidth: StyleSheet.hairlineWidth,
    marginTop: 12,
  },
  contactRow: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 14,
    gap: 12,
  },
  contactText: { flex: 1, fontSize: 15 },
  descBlock: {
    padding: 16,
    marginTop: 12,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  sectionHeading: {
    fontSize: 12,
    textTransform: "uppercase",
    letterSpacing: 0.6,
    marginBottom: 8,
  },
  descText: { fontSize: 15, lineHeight: 22 },
  categoryHeading: { fontSize: 18, paddingHorizontal: 16, paddingBottom: 8 },
  productRow: {
    flexDirection: "row",
    marginHorizontal: 16,
    marginBottom: 8,
    padding: 14,
    borderWidth: StyleSheet.hairlineWidth,
  },
  productLeft: { flex: 1 },
  productTopLine: { flexDirection: "row", alignItems: "flex-start", gap: 8 },
  productName: { fontSize: 15, flex: 1, lineHeight: 20 },
  availableDot: { paddingHorizontal: 8, paddingVertical: 3 },
  availableText: { fontSize: 11 },
  productPrice: { fontSize: 16, marginTop: 6 },
  noProdText: { textAlign: "center", fontSize: 15 },
  fabWrap: { position: "absolute", left: 0, right: 0, alignItems: "center" },
  fab: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
    paddingHorizontal: 32,
    paddingVertical: 15,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.18,
    shadowRadius: 10,
    elevation: 8,
  },
  fabLabel: { fontSize: 16 },
});
