import { useState } from "react";
import {
  ScrollView,
  View,
  Text,
  TextInput,
  StyleSheet,
  Pressable,
  Alert,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import { Redirect, useRouter } from "expo-router";

import { COLORS } from "../constants/colors";
import SectionTitle from "../components/SectionTitle";
import PrimaryButton from "../components/PrimaryButton";

import { useApp } from "../context/AppContext";
import {
  submitFeedback,
  type FeedbackType,
} from "../services/feedback.service";

type Option = {
  type: FeedbackType;
  label: string;
  icon: keyof typeof Ionicons.glyphMap;
  color: string;
};

const OPTIONS: Option[] = [
  {
    type: "TRUCK_DID_NOT_PASS",
    label: "El camión no pasó",
    icon: "alert-circle-outline",
    color: "#EF4444",
  },
  {
    type: "RATING",
    label: "Calificar el servicio",
    icon: "star-outline",
    color: "#F59E0B",
  },
  {
    type: "SUGGESTION",
    label: "Sugerencia",
    icon: "bulb-outline",
    color: "#3B82F6",
  },
  {
    type: "OTHER",
    label: "Otro",
    icon: "chatbubble-outline",
    color: "#6B7280",
  },
];

export default function FeedbackScreen() {
  const { user } = useApp();
  const router = useRouter();

  const [selectedType, setSelectedType] = useState<FeedbackType>(
    "TRUCK_DID_NOT_PASS",
  );
  const [message, setMessage] = useState("");
  const [rating, setRating] = useState<number | undefined>(undefined);
  const [submitting, setSubmitting] = useState(false);

  if (!user) return <Redirect href="/login" />;

  const handleSubmit = async () => {
    if (!message.trim()) {
      Alert.alert("Mensaje vacío", "Cuéntanos qué pasó.");
      return;
    }
    try {
      setSubmitting(true);
      const payload: { type: FeedbackType; message: string; rating?: number } =
        { type: selectedType, message };
      if (selectedType === "RATING" && rating) payload.rating = rating;
      await submitFeedback(payload);
      Alert.alert("Gracias", "Tu retroalimentación fue enviada.");
      setMessage("");
      setRating(undefined);
      router.back();
    } catch (err) {
      Alert.alert("Error", err instanceof Error ? err.message : "No se pudo enviar.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: COLORS.background }}>
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ padding: 20, paddingBottom: 120 }}
      >
        <SectionTitle title="Buzón de retroalimentación" />

        <Text style={styles.subtitle}>
          Reporta incidencias o califica el servicio. Tu mensaje llega
          directamente al equipo operativo.
        </Text>

        <Text style={styles.label}>Tipo de mensaje</Text>
        <View style={styles.optionsGrid}>
          {OPTIONS.map((opt) => {
            const active = selectedType === opt.type;
            return (
              <Pressable
                key={opt.type}
                onPress={() => setSelectedType(opt.type)}
                style={[
                  styles.optionCard,
                  active && { borderColor: opt.color, borderWidth: 2 },
                ]}
              >
                <Ionicons name={opt.icon} size={24} color={opt.color} />
                <Text style={styles.optionLabel}>{opt.label}</Text>
              </Pressable>
            );
          })}
        </View>

        {selectedType === "RATING" && (
          <>
            <Text style={styles.label}>Calificación</Text>
            <View style={styles.starsRow}>
              {[1, 2, 3, 4, 5].map((n) => (
                <Pressable key={n} onPress={() => setRating(n)}>
                  <Ionicons
                    name={rating && n <= rating ? "star" : "star-outline"}
                    size={34}
                    color="#F59E0B"
                    style={{ marginRight: 8 }}
                  />
                </Pressable>
              ))}
            </View>
          </>
        )}

        <Text style={styles.label}>Mensaje</Text>
        <TextInput
          style={styles.textArea}
          placeholder="Cuéntanos qué pasó..."
          placeholderTextColor="#9CA3AF"
          value={message}
          onChangeText={setMessage}
          multiline
          numberOfLines={5}
        />

        <View style={{ height: 16 }} />
        <PrimaryButton
          title={submitting ? "Enviando..." : "Enviar"}
          onPress={handleSubmit}
        />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  subtitle: {
    color: "#6B7280",
    fontSize: 14,
    marginBottom: 20,
    marginLeft: 12,
  },
  label: {
    fontSize: 13,
    fontWeight: "700",
    color: "#374151",
    marginTop: 8,
    marginBottom: 10,
    marginLeft: 12,
  },
  optionsGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
  },
  optionCard: {
    width: "48%",
    backgroundColor: "#FFFFFF",
    borderRadius: 14,
    padding: 14,
    marginBottom: 12,
    borderColor: "transparent",
    borderWidth: 2,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.05,
    shadowRadius: 6,
    elevation: 2,
  },
  optionLabel: {
    fontSize: 13,
    fontWeight: "600",
    color: "#1F2937",
    marginTop: 8,
  },
  starsRow: {
    flexDirection: "row",
    marginLeft: 12,
    marginBottom: 10,
  },
  textArea: {
    backgroundColor: "#FFFFFF",
    borderRadius: 14,
    padding: 14,
    minHeight: 110,
    fontSize: 14,
    color: "#1F2937",
    textAlignVertical: "top",
    marginHorizontal: 2,
  },
});
