import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Modal,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
} from "react-native";
import { X, Calendar } from "lucide-react-native";
import DateTimePicker from "@react-native-community/datetimepicker";
import { PRIMARY } from "@/constants/colors";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";
import { Etape } from "@/types/tasks.types";
import { useCreateEtape, useUpdateEtape } from "@/hooks/etapes";

type EtapeSheetProps = {
  visible: boolean;
  onClose: () => void;
  tabloId: string;
  etape?: Etape | null; // null = create mode
};

export default function EtapeSheet({ visible, onClose, tabloId, etape }: EtapeSheetProps) {
  const colorScheme = useColorScheme();
  const isDark = colorScheme === "dark";
  const bgColor = useThemeColor({ light: "#ffffff", dark: "#1f2937" }, "background");
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");
  const inputBg = useThemeColor({ light: "#f1f5f9", dark: "#374151" }, "background");
  const borderColor = isDark ? "#374151" : "#e5e7eb";
  const subtextColor = useThemeColor({ light: "#6b7280", dark: "#9ca3af" }, "text");

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [dueDate, setDueDate] = useState<Date | null>(null);
  const [showDatePicker, setShowDatePicker] = useState(false);

  const { mutate: createEtape, isPending: isCreating } = useCreateEtape();
  const { mutate: updateEtape, isPending: isUpdating } = useUpdateEtape();
  const isPending = isCreating || isUpdating;

  const isEditMode = !!etape;

  useEffect(() => {
    if (etape) {
      setTitle(etape.title);
      setDescription(etape.description ?? "");
      setDueDate(etape.due_date ? new Date(etape.due_date) : null);
    } else {
      setTitle("");
      setDescription("");
      setDueDate(null);
    }
    setShowDatePicker(false);
  }, [etape, visible]);

  const formatDueDate = (date: Date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
  };

  const handleSave = () => {
    if (!title.trim()) return;

    const dueDateStr = dueDate ? formatDueDate(dueDate) : null;

    if (isEditMode && etape) {
      updateEtape(
        {
          id: etape.id,
          tabloId,
          title: title.trim(),
          description: description.trim() || null,
          due_date: dueDateStr,
        },
        { onSuccess: onClose }
      );
    } else {
      createEtape(
        {
          tabloId,
          title: title.trim(),
          description: description.trim() || null,
          due_date: dueDateStr,
        },
        { onSuccess: onClose }
      );
    }
  };

  const dueDateDisplay = dueDate
    ? dueDate.toLocaleDateString("fr-FR", { day: "numeric", month: "long", year: "numeric" })
    : "Aucune";

  return (
    <Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.overlay}
      >
        <View style={[styles.sheet, { backgroundColor: bgColor }]}>
          <View style={[styles.sheetHeader, { borderBottomColor: borderColor }]}>
            <Text style={[styles.sheetTitle, { color: textColor }]}>
              {isEditMode ? "Modifier l'étape" : "Nouvelle étape"}
            </Text>
            <TouchableOpacity onPress={onClose}>
              <X size={22} color={textColor} />
            </TouchableOpacity>
          </View>

          <View style={styles.sheetBody}>
            <Text style={[styles.label, { color: textColor }]}>Titre</Text>
            <TextInput
              style={[styles.input, { backgroundColor: inputBg, color: textColor }]}
              value={title}
              onChangeText={setTitle}
              placeholder="Nom de l'étape"
              placeholderTextColor="#9ca3af"
              autoFocus
            />

            <Text style={[styles.label, { color: textColor }]}>Description</Text>
            <TextInput
              style={[styles.input, styles.textArea, { backgroundColor: inputBg, color: textColor }]}
              value={description}
              onChangeText={setDescription}
              placeholder="Description (optionnel)"
              placeholderTextColor="#9ca3af"
              multiline
              numberOfLines={3}
            />

            <Text style={[styles.label, { color: textColor }]}>Date limite</Text>
            <TouchableOpacity
              style={[styles.pickerButton, { backgroundColor: inputBg }]}
              onPress={() => setShowDatePicker(true)}
            >
              <Calendar size={16} color={subtextColor} />
              <Text style={[styles.pickerText, { color: dueDate ? textColor : subtextColor }]}>
                {dueDateDisplay}
              </Text>
              {dueDate && (
                <TouchableOpacity onPress={() => setDueDate(null)}>
                  <Text style={{ color: "#ef4444", fontSize: 13 }}>Retirer</Text>
                </TouchableOpacity>
              )}
            </TouchableOpacity>

            {showDatePicker && (
              <DateTimePicker
                value={dueDate ?? new Date()}
                mode="date"
                display={Platform.OS === "ios" ? "spinner" : "default"}
                onChange={(event, date) => {
                  setShowDatePicker(Platform.OS !== "ios");
                  if (date) setDueDate(date);
                }}
              />
            )}
          </View>

          <TouchableOpacity
            style={[styles.saveButton, !title.trim() && styles.saveButtonDisabled]}
            onPress={handleSave}
            disabled={!title.trim() || isPending}
          >
            <Text style={styles.saveButtonText}>
              {isPending ? "..." : isEditMode ? "Enregistrer" : "Créer"}
            </Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    justifyContent: "flex-end",
    backgroundColor: "rgba(0,0,0,0.4)",
  },
  sheet: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    paddingBottom: 34,
  },
  sheetHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  sheetTitle: {
    fontSize: 17,
    fontWeight: "700",
  },
  sheetBody: {
    padding: 16,
    gap: 12,
  },
  label: {
    fontSize: 14,
    fontWeight: "600",
  },
  input: {
    borderRadius: 10,
    paddingHorizontal: 14,
    paddingVertical: 12,
    fontSize: 15,
  },
  textArea: {
    minHeight: 80,
    textAlignVertical: "top",
  },
  pickerButton: {
    flexDirection: "row",
    alignItems: "center",
    borderRadius: 10,
    paddingHorizontal: 14,
    paddingVertical: 12,
    gap: 10,
  },
  pickerText: {
    flex: 1,
    fontSize: 15,
  },
  saveButton: {
    marginHorizontal: 16,
    backgroundColor: PRIMARY,
    borderRadius: 12,
    paddingVertical: 14,
    alignItems: "center",
  },
  saveButtonDisabled: {
    opacity: 0.5,
  },
  saveButtonText: {
    color: "#ffffff",
    fontSize: 16,
    fontWeight: "700",
  },
});
