import Select from "@/components/Select";
import { IconSymbol } from "@/components/ui/icon-symbol";
import { queryGpsData } from "@/controller/DeviceController";
import { queryUpdateFishingLogs } from "@/controller/TripController";
import { useI18n } from "@/hooks/use-i18n";
import { showErrorToast, showSuccessToast } from "@/services/toast_service";
import { useFishes } from "@/state/use-fish";
import { useTrip } from "@/state/use-trip";
import { zodResolver } from "@hookform/resolvers/zod";
import React from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import {
  KeyboardAvoidingView,
  Modal,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { z } from "zod";
import { InfoSection } from "./NetDetailModal/components";
import styles from "./style/CreateOrUpdateHaulModal.styles";

interface CreateOrUpdateHaulModalProps {
  isVisible: boolean;
  onClose: () => void;
  fishingLog?: Model.FishingLog | null;
  fishingLogIndex?: number;
}
const UNITS = ["con", "kg", "tấn"] as const;
type Unit = (typeof UNITS)[number];

const UNITS_OPTIONS = UNITS.map((unit) => ({
  label: unit,
  value: unit.toString(),
}));

const SIZE_UNITS = ["cm", "m"] as const;
type SizeUnit = (typeof SIZE_UNITS)[number];

const SIZE_UNITS_OPTIONS = SIZE_UNITS.map((unit) => ({
  label: unit,
  value: unit,
}));

// Zod schema cho 1 dòng cá
const fishItemSchema = z.object({
  id: z.number().min(1, ""),
  quantity: z.number({ invalid_type_error: "" }).positive(""),
  unit: z.enum(UNITS, { required_error: "" }),
  size: z.number({ invalid_type_error: "" }).positive("").optional(),
  sizeUnit: z.enum(SIZE_UNITS),
});

// Schema tổng: mảng các item
const formSchema = z.object({
  fish: z.array(fishItemSchema).min(1, ""),
});
type FormValues = z.infer<typeof formSchema>;

const defaultItem = (): FormValues["fish"][number] => ({
  id: -1,
  quantity: 1,
  unit: "con",
  size: undefined,
  sizeUnit: "cm",
});

const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
  isVisible,
  onClose,
  fishingLog,
  fishingLogIndex,
}) => {
  const { t } = useI18n();
  const [isCreateMode, setIsCreateMode] = React.useState(!fishingLog?.info);
  const [isEditing, setIsEditing] = React.useState(false);
  const [expandedFishIndices, setExpandedFishIndices] = React.useState<
    number[]
  >([]);
  const { trip, getTrip } = useTrip();
  const { control, handleSubmit, formState, watch, reset } =
    useForm<FormValues>({
      resolver: zodResolver(formSchema),
      defaultValues: {
        fish: [defaultItem()],
      },
      mode: "onSubmit",
    });
  const { fishSpecies, getFishSpecies } = useFishes();
  const { errors } = formState;
  if (!fishSpecies) {
    getFishSpecies();
  }
  const { fields, append, remove } = useFieldArray({
    control,
    name: "fish",
    keyName: "_id", // tránh đụng key
  });

  const handleToggleExpanded = (index: number) => {
    setExpandedFishIndices((prev) =>
      prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index]
    );
  };

  const onSubmit = async (values: FormValues) => {
    // Ensure species list is available so we can populate name/rarity
    if (!fishSpecies || fishSpecies.length === 0) {
      showErrorToast(t("trip.createHaulModal.fishListNotReady"));
      return;
    }
    // Helper to map form rows -> API info entries (single place)
    const buildInfo = (rows: FormValues["fish"]) =>
      rows.map((item) => {
        const meta = fishSpecies.find((f) => f.id === item.id);
        return {
          fish_species_id: item.id,
          fish_name: meta?.name ?? "",
          catch_number: item.quantity,
          catch_unit: item.unit,
          fish_size: item.size,
          fish_rarity: meta?.rarity_level ?? null,
          fish_condition: "",
          gear_usage: "",
        } as unknown;
      });

    try {
      const gpsResp = await queryGpsData();
      if (!gpsResp.data) {
        showErrorToast(t("trip.createHaulModal.gpsError"));
        return;
      }
      const gpsData = gpsResp.data;

      const info = buildInfo(values.fish) as any;

      // Base payload fields shared between create and update
      const base: Partial<Model.FishingLog> = {
        fishing_log_id: fishingLog?.fishing_log_id || "",
        trip_id: trip?.id || "",
        start_at: fishingLog?.start_at!,
        start_lat: fishingLog?.start_lat!,
        start_lon: fishingLog?.start_lon!,
        weather_description:
          fishingLog?.weather_description || "Nắng đẹp, Trời nhiều mây",
        info,
        sync: true,
      };

      // Build final payload depending on create vs update
      const body: Model.FishingLog =
        fishingLog?.status == 0
          ? ({
              ...base,
              haul_lat: gpsData.lat,
              haul_lon: gpsData.lon,
              end_at: new Date(),
              status: 1,
            } as Model.FishingLog)
          : ({
              ...base,
              haul_lat: fishingLog?.haul_lat,
              haul_lon: fishingLog?.haul_lon,
              end_at: fishingLog?.end_at,
              status: fishingLog?.status,
            } as Model.FishingLog);
      // console.log("Body: ", body);

      const resp = await queryUpdateFishingLogs(body);
      if (resp?.status === 200) {
        showSuccessToast(
          fishingLog?.fishing_log_id == null
            ? t("trip.createHaulModal.addSuccess")
            : t("trip.createHaulModal.updateSuccess")
        );
        getTrip();
        onClose();
      } else {
        showErrorToast(
          fishingLog?.fishing_log_id == null
            ? t("trip.createHaulModal.addError")
            : t("trip.createHaulModal.updateError")
        );
      }
    } catch (err) {
      console.error("onSubmit error:", err);
      showErrorToast(t("trip.createHaulModal.validationError"));
    }
  };

  // Initialize / reset form when modal visibility or haulData changes
  React.useEffect(() => {
    if (!isVisible) {
      // when modal closed, clear form to default
      reset({ fish: [defaultItem()] });
      setIsCreateMode(true);
      setIsEditing(false);
      setExpandedFishIndices([]);
      return;
    }

    // when modal opened, populate based on fishingLog
    if (fishingLog?.info === null) {
      // explicit null -> start with a single default item
      reset({ fish: [defaultItem()] });
      setIsCreateMode(true);
      setIsEditing(true); // allow editing for new haul
      setExpandedFishIndices([0]); // expand first item
    } else if (Array.isArray(fishingLog?.info) && fishingLog?.info.length > 0) {
      // map FishingLogInfo -> form rows
      const mapped = fishingLog.info.map((h) => ({
        id: h.fish_species_id ?? -1,
        quantity: (h.catch_number as number) ?? 1,
        unit: (h.catch_unit as Unit) ?? (defaultItem().unit as Unit),
        size: (h.fish_size as number) ?? undefined,
        sizeUnit: "cm" as SizeUnit,
      }));
      reset({ fish: mapped as any });
      setIsCreateMode(false);
      setIsEditing(false); // view mode by default
      setExpandedFishIndices([]); // all collapsed
    } else {
      // undefined or empty array -> default
      reset({ fish: [defaultItem()] });
      setIsCreateMode(true);
      setIsEditing(true); // allow editing for new haul
      setExpandedFishIndices([0]); // expand first item
    }
  }, [isVisible, fishingLog?.info, reset]);
  const renderRow = (item: any, index: number) => {
    const isExpanded = expandedFishIndices.includes(index);
    // Give expanded card highest zIndex, others get decreasing zIndex based on position
    const cardZIndex = isExpanded ? 1000 : 100 - index;

    return (
      <View key={item._id} style={[styles.fishCard, { zIndex: cardZIndex }]}>
        {/* Delete + Chevron buttons - top right corner */}
        <View
          style={{
            position: "absolute",
            top: 0,
            right: 0,
            zIndex: 9999,
            flexDirection: "row",
            alignItems: "center",
            padding: 8,
            gap: 8,
          }}
          pointerEvents="box-none"
        >
          {isEditing && (
            <TouchableOpacity
              onPress={() => remove(index)}
              style={{
                backgroundColor: "#FF3B30",
                borderRadius: 8,
                width: 40,
                height: 40,
                justifyContent: "center",
                alignItems: "center",
                shadowColor: "#000",
                shadowOpacity: 0.08,
                shadowRadius: 2,
                shadowOffset: { width: 0, height: 1 },
                elevation: 2,
              }}
              hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
              activeOpacity={0.7}
            >
              <IconSymbol name="trash" size={24} color="#fff" />
            </TouchableOpacity>
          )}
          <TouchableOpacity
            onPress={() => handleToggleExpanded(index)}
            style={{
              backgroundColor: "#007AFF",
              borderRadius: 8,
              width: 40,
              height: 40,
              justifyContent: "center",
              alignItems: "center",
              shadowColor: "#000",
              shadowOpacity: 0.08,
              shadowRadius: 2,
              shadowOffset: { width: 0, height: 1 },
              elevation: 2,
            }}
            hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
            activeOpacity={0.7}
          >
            <IconSymbol
              name={isExpanded ? "chevron.up" : "chevron.down"}
              size={24}
              color="#fff"
            />
          </TouchableOpacity>
        </View>

        {/* Header - visible when collapsed */}
        {!isExpanded && (
          <View style={{ paddingRight: 100 }}>
            {(() => {
              const fishId = watch(`fish.${index}.id`);
              const fishName = fishSpecies?.find((f) => f.id === fishId)?.name;
              const quantity = watch(`fish.${index}.quantity`);
              const unit = watch(`fish.${index}.unit`);

              return (
                <View style={styles.fishCardHeaderContent}>
                  <Text style={styles.fishCardTitle}>
                    {fishName || t("trip.createHaulModal.selectFish")}:
                  </Text>
                  <Text style={styles.fishCardSubtitle}>
                    {fishName ? `${quantity} ${unit}` : "---"}
                  </Text>
                </View>
              );
            })()}
          </View>
        )}

        {/* Form - visible when expanded */}
        {isExpanded && (
          <View style={{ paddingRight: 10 }}>
            {/* Species dropdown */}
            <Controller
              control={control}
              name={`fish.${index}.id`}
              render={({ field: { value, onChange } }) => (
                <View style={[styles.fieldGroup, { marginTop: 20 }]}>
                  <Text style={styles.label}>
                    {t("trip.createHaulModal.fishName")}
                  </Text>
                  <Select
                    options={fishSpecies!.map((fish) => ({
                      label: fish.name,
                      value: fish.id,
                    }))}
                    value={value}
                    onChange={onChange}
                    placeholder={t("trip.createHaulModal.selectFish")}
                    disabled={!isEditing}
                  />
                  {errors.fish?.[index]?.id && (
                    <Text style={styles.errorText}>
                      {t("trip.createHaulModal.selectFish")}
                    </Text>
                  )}
                </View>
              )}
            />

            {/* Số lượng & Đơn vị cùng hàng */}
            <View style={{ flexDirection: "row", gap: 12 }}>
              <View style={{ flex: 1 }}>
                <Controller
                  control={control}
                  name={`fish.${index}.quantity`}
                  render={({ field: { value, onChange, onBlur } }) => (
                    <View style={styles.fieldGroup}>
                      <Text style={styles.label}>
                        {t("trip.createHaulModal.quantity")}
                      </Text>
                      <TextInput
                        keyboardType="numeric"
                        value={String(value ?? "")}
                        onBlur={onBlur}
                        onChangeText={(t) =>
                          onChange(Number(t.replace(/,/g, ".")) || 0)
                        }
                        style={[
                          styles.input,
                          !isEditing && styles.inputDisabled,
                        ]}
                        editable={isEditing}
                      />
                      {errors.fish?.[index]?.quantity && (
                        <Text style={styles.errorText}>
                          {t("trip.createHaulModal.quantity")}
                        </Text>
                      )}
                    </View>
                  )}
                />
              </View>
              <View style={{ flex: 1 }}>
                <Controller
                  control={control}
                  name={`fish.${index}.unit`}
                  render={({ field: { value, onChange } }) => (
                    <View style={styles.fieldGroup}>
                      <Text style={styles.label}>
                        {t("trip.createHaulModal.unit")}
                      </Text>
                      <Select
                        options={UNITS_OPTIONS.map((unit) => ({
                          label: unit.label,
                          value: unit.value,
                        }))}
                        value={value}
                        onChange={onChange}
                        placeholder={t("trip.createHaulModal.unit")}
                        disabled={!isEditing}
                        listStyle={{ maxHeight: 100 }}
                      />
                      {errors.fish?.[index]?.unit && (
                        <Text style={styles.errorText}>
                          {t("trip.createHaulModal.unit")}
                        </Text>
                      )}
                    </View>
                  )}
                />
              </View>
            </View>

            {/* Size (optional) + Unit dropdown */}
            <View style={{ flexDirection: "row", gap: 12 }}>
              <View style={{ flex: 1 }}>
                <Controller
                  control={control}
                  name={`fish.${index}.size`}
                  render={({ field: { value, onChange, onBlur } }) => (
                    <View style={styles.fieldGroup}>
                      <Text style={styles.label}>
                        {t("trip.createHaulModal.size")} (
                        {t("trip.createHaulModal.optional")})
                      </Text>
                      <TextInput
                        keyboardType="numeric"
                        value={value ? String(value) : ""}
                        onBlur={onBlur}
                        onChangeText={(t) =>
                          onChange(t ? Number(t.replace(/,/g, ".")) : undefined)
                        }
                        style={[
                          styles.input,
                          !isEditing && styles.inputDisabled,
                        ]}
                        editable={isEditing}
                      />
                      {errors.fish?.[index]?.size && (
                        <Text style={styles.errorText}>
                          {t("trip.createHaulModal.size")}
                        </Text>
                      )}
                    </View>
                  )}
                />
              </View>
              <View style={{ flex: 1 }}>
                <Controller
                  control={control}
                  name={`fish.${index}.sizeUnit`}
                  render={({ field: { value, onChange } }) => (
                    <View style={styles.fieldGroup}>
                      <Text style={styles.label}>
                        {t("trip.createHaulModal.unit")}
                      </Text>
                      <Select
                        options={SIZE_UNITS_OPTIONS}
                        value={value}
                        onChange={onChange}
                        placeholder={t("trip.createHaulModal.unit")}
                        disabled={!isEditing}
                        listStyle={{ maxHeight: 80 }}
                      />
                    </View>
                  )}
                />
              </View>
            </View>
          </View>
        )}
      </View>
    );
  };

  return (
    <Modal
      visible={isVisible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        keyboardVerticalOffset={60}
      >
        <View style={styles.container}>
          {/* Header */}
          <View style={styles.header}>
            <Text style={styles.title}>
              {isCreateMode
                ? t("trip.createHaulModal.addFish")
                : t("trip.createHaulModal.edit")}
            </Text>
            <View style={styles.headerButtons}>
              {isEditing ? (
                <>
                  {!isCreateMode && (
                    <TouchableOpacity
                      onPress={() => {
                        setIsEditing(false);
                        reset(); // reset to previous values
                      }}
                      style={[
                        styles.saveButton,
                        { backgroundColor: "#6c757d" },
                      ]}
                    >
                      <Text style={styles.saveButtonText}>
                        {t("trip.createHaulModal.cancel")}
                      </Text>
                    </TouchableOpacity>
                  )}
                  <TouchableOpacity
                    onPress={handleSubmit(onSubmit)}
                    style={styles.saveButton}
                  >
                    <Text style={styles.saveButtonText}>
                      {t("trip.createHaulModal.save")}
                    </Text>
                  </TouchableOpacity>
                </>
              ) : (
                !isCreateMode && (
                  <TouchableOpacity
                    onPress={() => setIsEditing(true)}
                    style={[styles.saveButton, { backgroundColor: "#17a2b8" }]}
                  >
                    <Text style={styles.saveButtonText}>
                      {t("trip.createHaulModal.edit")}
                    </Text>
                  </TouchableOpacity>
                )
              )}
              <TouchableOpacity onPress={onClose} style={styles.closeButton}>
                <View style={styles.closeIconButton}>
                  <IconSymbol name="xmark" size={24} color="#fff" />
                </View>
              </TouchableOpacity>
            </View>
          </View>

          {/* Content */}
          <ScrollView style={styles.content}>
            {/* Info Section */}
            <InfoSection fishingLog={fishingLog!} stt={fishingLogIndex} />

            {/* Fish List */}
            {fields.map((item, index) => renderRow(item, index))}

            {/* Add Button - only show when editing */}
            {isEditing && (
              <TouchableOpacity
                onPress={() => append(defaultItem())}
                style={styles.addButton}
              >
                <Text style={styles.addButtonText}>
                  + {t("trip.createHaulModal.addFish")}
                </Text>
              </TouchableOpacity>
            )}

            {/* Error Message */}
            {errors.fish && (
              <Text style={styles.errorText}>
                {t("trip.createHaulModal.validationError")}
              </Text>
            )}
          </ScrollView>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
};

export default CreateOrUpdateHaulModal;
