import React from "react";
import { View, Text, TouchableOpacity, StyleSheet, Alert } from "react-native";
import { ChevronDown, ChevronRight } from "lucide-react-native";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";
import { Etape } from "@/types/tasks.types";

type EtapeSectionProps = {
  etape: Etape | null; // null = "Sans Étape"
  taskCount: number;
  isCollapsed: boolean;
  onToggle: () => void;
  onEdit?: (etape: Etape) => void;
  onDelete?: (etape: Etape) => void;
  children: React.ReactNode;
};

export default function EtapeSection({
  etape,
  taskCount,
  isCollapsed,
  onToggle,
  onEdit,
  onDelete,
  children,
}: EtapeSectionProps) {
  const colorScheme = useColorScheme();
  const isDark = colorScheme === "dark";
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");
  const bgColor = useThemeColor({ light: "#f1f5f9", dark: "#1e293b" }, "background");
  const iconColor = isDark ? "#9ca3af" : "#6b7280";

  const title = etape ? etape.title : "Sans Étape";
  const ChevronIcon = isCollapsed ? ChevronRight : ChevronDown;

  const handleLongPress = () => {
    if (!etape) return;
    Alert.alert(etape.title, undefined, [
      { text: "Modifier", onPress: () => onEdit?.(etape) },
      {
        text: "Supprimer",
        style: "destructive",
        onPress: () => {
          Alert.alert(
            "Supprimer l'étape",
            "Les tâches associées seront déplacées dans \"Sans Étape\".",
            [
              { text: "Annuler", style: "cancel" },
              { text: "Supprimer", style: "destructive", onPress: () => onDelete?.(etape) },
            ]
          );
        },
      },
      { text: "Annuler", style: "cancel" },
    ]);
  };

  return (
    <View>
      <TouchableOpacity
        style={[styles.header, { backgroundColor: bgColor }]}
        onPress={onToggle}
        onLongPress={handleLongPress}
        activeOpacity={0.7}
      >
        <ChevronIcon size={18} color={iconColor} />
        <Text style={[styles.title, { color: textColor }]} numberOfLines={1}>
          {title}
        </Text>
        <View style={styles.badge}>
          <Text style={styles.badgeText}>{taskCount}</Text>
        </View>
      </TouchableOpacity>
      {!isCollapsed && children}
    </View>
  );
}

const styles = StyleSheet.create({
  header: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
    paddingHorizontal: 16,
    gap: 8,
  },
  title: {
    flex: 1,
    fontSize: 14,
    fontWeight: "700",
  },
  badge: {
    backgroundColor: "#6b7280",
    borderRadius: 10,
    paddingHorizontal: 8,
    paddingVertical: 2,
  },
  badgeText: {
    color: "#ffffff",
    fontSize: 12,
    fontWeight: "600",
  },
});
