import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Modal,
  ScrollView,
  ActivityIndicator,
  Platform,
  Alert,
} from "react-native";
import { Feather } from "@expo/vector-icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as Haptics from "expo-haptics";
import { customFetch } from "@workspace/api-client-react";
import { useColors } from "@/hooks/useColors";
import { useSafeAreaInsets } from "react-native-safe-area-context";

interface QuoteItem {
  name: string;
  qty: string;
  unit: string;
}

interface Props {
  visible: boolean;
  vendorId: number;
  vendorName: string;
  onClose: () => void;
}

export default function QuoteModal({ visible, vendorId, vendorName, onClose }: Props) {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const queryClient = useQueryClient();

  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [items, setItems] = useState<QuoteItem[]>([{ name: "", qty: "1", unit: "pcs" }]);
  const [formError, setFormError] = useState("");

  const mutation = useMutation({
    mutationFn: (data: object) =>
      customFetch("/api/quote-requests", {
        method: "POST",
        body: JSON.stringify(data),
      }),
    onSuccess: async () => {
      await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      queryClient.invalidateQueries({ queryKey: ["my-quotes"] });
      handleClose();
      Alert.alert("Quote Sent!", "The vendor will be in touch with you soon.");
    },
    onError: (e: Error) => {
      setFormError(e.message || "Failed to send quote. Please try again.");
    },
  });

  const handleClose = () => {
    setSubject("");
    setMessage("");
    setItems([{ name: "", qty: "1", unit: "pcs" }]);
    setFormError("");
    onClose();
  };

  const addItem = () =>
    setItems((prev) => [...prev, { name: "", qty: "1", unit: "pcs" }]);

  const removeItem = (i: number) =>
    setItems((prev) => prev.filter((_, idx) => idx !== i));

  const updateItem = (i: number, field: keyof QuoteItem, value: string) => {
    setItems((prev) =>
      prev.map((item, idx) => (idx === i ? { ...item, [field]: value } : item))
    );
  };

  const handleSend = () => {
    if (!subject.trim()) {
      setFormError("Subject is required.");
      return;
    }
    const validItems = items.filter((it) => it.name.trim());
    mutation.mutate({
      vendorId,
      subject: subject.trim(),
      message: message.trim(),
      items: validItems.map((it) => ({
        name: it.name.trim(),
        qty: parseInt(it.qty, 10) || 1,
        unit: it.unit.trim() || "pcs",
      })),
    });
  };

  const bottomPad = Platform.OS === "web" ? 34 : insets.bottom;

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={handleClose}
    >
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <View
          style={[
            styles.handle,
            { backgroundColor: colors.border },
          ]}
        />

        <View
          style={[
            styles.modalHeader,
            { borderBottomColor: colors.border },
          ]}
        >
          <TouchableOpacity onPress={handleClose} style={styles.headerBtn} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
            <Feather name="x" size={22} color={colors.foreground} />
          </TouchableOpacity>
          <Text
            style={[
              styles.modalTitle,
              { color: colors.foreground, fontFamily: "Inter_700Bold" },
            ]}
          >
            Request Quote
          </Text>
          <TouchableOpacity
            onPress={handleSend}
            disabled={mutation.isPending}
            style={[
              styles.sendBtn,
              {
                backgroundColor: mutation.isPending
                  ? colors.mutedForeground
                  : colors.primary,
                borderRadius: colors.radius,
              },
            ]}
          >
            {mutation.isPending ? (
              <ActivityIndicator size="small" color={colors.primaryForeground} />
            ) : (
              <Text
                style={[
                  styles.sendBtnText,
                  { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
                ]}
              >
                Send
              </Text>
            )}
          </TouchableOpacity>
        </View>

        <ScrollView
          contentContainerStyle={[styles.form, { paddingBottom: bottomPad + 40 }]}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <Text
            style={[
              styles.toLabel,
              { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
            ]}
          >
            To: {vendorName}
          </Text>

          {formError.length > 0 && (
            <View
              style={[
                styles.errorBox,
                { backgroundColor: colors.destructive + "18", borderRadius: colors.radius },
              ]}
            >
              <Text
                style={[
                  styles.errorText,
                  { color: colors.destructive, fontFamily: "Inter_400Regular" },
                ]}
              >
                {formError}
              </Text>
            </View>
          )}

          <Text
            style={[
              styles.fieldLabel,
              { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
            ]}
          >
            Subject *
          </Text>
          <TextInput
            value={subject}
            onChangeText={setSubject}
            placeholder="e.g. Quote for construction materials"
            placeholderTextColor={colors.mutedForeground}
            style={[
              styles.input,
              {
                color: colors.foreground,
                backgroundColor: colors.muted,
                borderColor: colors.border,
                borderRadius: colors.radius,
                fontFamily: "Inter_400Regular",
              },
            ]}
          />

          <Text
            style={[
              styles.fieldLabel,
              { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
            ]}
          >
            Message
          </Text>
          <TextInput
            value={message}
            onChangeText={setMessage}
            placeholder="Delivery requirements, timeline, specifications..."
            placeholderTextColor={colors.mutedForeground}
            multiline
            numberOfLines={3}
            textAlignVertical="top"
            style={[
              styles.textarea,
              {
                color: colors.foreground,
                backgroundColor: colors.muted,
                borderColor: colors.border,
                borderRadius: colors.radius,
                fontFamily: "Inter_400Regular",
              },
            ]}
          />

          <View style={styles.itemsHeader}>
            <Text
              style={[
                styles.fieldLabel,
                { color: colors.mutedForeground, fontFamily: "Inter_500Medium", marginBottom: 0 },
              ]}
            >
              Items
            </Text>
            <TouchableOpacity
              onPress={addItem}
              style={[
                styles.addItemBtn,
                { borderColor: colors.primary, borderRadius: 6 },
              ]}
            >
              <Feather name="plus" size={13} color={colors.primary} />
              <Text
                style={[
                  styles.addItemText,
                  { color: colors.primary, fontFamily: "Inter_500Medium" },
                ]}
              >
                Add item
              </Text>
            </TouchableOpacity>
          </View>

          {items.map((item, i) => (
            <View
              key={i}
              style={[
                styles.itemCard,
                {
                  backgroundColor: colors.card,
                  borderColor: colors.border,
                  borderRadius: colors.radius,
                },
              ]}
            >
              <TextInput
                value={item.name}
                onChangeText={(v) => updateItem(i, "name", v)}
                placeholder="Item name or description"
                placeholderTextColor={colors.mutedForeground}
                style={[
                  styles.itemNameInput,
                  {
                    color: colors.foreground,
                    borderBottomColor: colors.border,
                    fontFamily: "Inter_400Regular",
                  },
                ]}
              />
              <View style={styles.itemMeta}>
                <TextInput
                  value={item.qty}
                  onChangeText={(v) => updateItem(i, "qty", v)}
                  keyboardType="numeric"
                  placeholder="Qty"
                  placeholderTextColor={colors.mutedForeground}
                  style={[
                    styles.qtyInput,
                    {
                      color: colors.foreground,
                      backgroundColor: colors.muted,
                      borderColor: colors.border,
                      borderRadius: 6,
                      fontFamily: "Inter_400Regular",
                    },
                  ]}
                />
                <TextInput
                  value={item.unit}
                  onChangeText={(v) => updateItem(i, "unit", v)}
                  placeholder="Unit"
                  placeholderTextColor={colors.mutedForeground}
                  style={[
                    styles.unitInput,
                    {
                      color: colors.foreground,
                      backgroundColor: colors.muted,
                      borderColor: colors.border,
                      borderRadius: 6,
                      fontFamily: "Inter_400Regular",
                      flex: 1,
                    },
                  ]}
                />
                {items.length > 1 && (
                  <TouchableOpacity
                    onPress={() => removeItem(i)}
                    style={styles.removeBtn}
                    hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                  >
                    <Feather name="trash-2" size={15} color={colors.destructive} />
                  </TouchableOpacity>
                )}
              </View>
            </View>
          ))}
        </ScrollView>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, paddingTop: 12 },
  handle: { width: 36, height: 4, borderRadius: 2, alignSelf: "center", marginBottom: 12 },
  modalHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  headerBtn: { padding: 2 },
  modalTitle: { fontSize: 17 },
  sendBtn: { paddingHorizontal: 18, paddingVertical: 8, minWidth: 68, alignItems: "center" },
  sendBtnText: { fontSize: 15 },
  form: { padding: 16, gap: 6 },
  toLabel: { fontSize: 14, marginBottom: 12 },
  errorBox: { padding: 12, marginBottom: 8 },
  errorText: { fontSize: 13 },
  fieldLabel: { fontSize: 13, marginBottom: 6, marginTop: 4 },
  input: { height: 48, paddingHorizontal: 14, fontSize: 15, borderWidth: 1 },
  textarea: { paddingHorizontal: 14, paddingVertical: 12, fontSize: 15, borderWidth: 1, minHeight: 84 },
  itemsHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginTop: 8, marginBottom: 8 },
  addItemBtn: { flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 10, paddingVertical: 5, borderWidth: 1 },
  addItemText: { fontSize: 13 },
  itemCard: { borderWidth: StyleSheet.hairlineWidth, marginBottom: 8, overflow: "hidden" },
  itemNameInput: { paddingHorizontal: 12, paddingVertical: 10, fontSize: 15, borderBottomWidth: StyleSheet.hairlineWidth },
  itemMeta: { flexDirection: "row", alignItems: "center", padding: 8, gap: 8 },
  qtyInput: { width: 60, height: 36, textAlign: "center", borderWidth: 1, fontSize: 14 },
  unitInput: { height: 36, paddingHorizontal: 8, borderWidth: 1, fontSize: 14 },
  removeBtn: { padding: 6 },
});
