import Select from "@/components/Select";
import { useFishes } from "@/state/use-fish";
import { zodResolver } from "@hookform/resolvers/zod";
import React from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { Button, FlatList, Modal, Text, TextInput, View } from "react-native";
import { z } from "zod";

interface CreateOrUpdateHaulModalProps {
  isVisible: boolean;
  onClose: () => void;
  haulData?: Model.FishingLogInfo[] | null;
}

const UNITS = ["con", "kg", "tấn"] as const;
type Unit = (typeof UNITS)[number];

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

// Zod schema cho 1 dòng cá
const fishItemSchema = z.object({
  id: z.number().min(1, "Chọn loài cá"),
  quantity: z
    .number({ invalid_type_error: "Số lượng phải là số" })
    .positive("Số lượng > 0"),
  unit: z.enum(UNITS, { required_error: "Chọn đơn vị" }),
  size: z
    .number({ invalid_type_error: "Kích thước phải là số" })
    .positive("Kích thước > 0")
    .optional(),
});

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

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

const CreateOrUpdateHaulModal: React.FC<CreateOrUpdateHaulModalProps> = ({
  isVisible,
  onClose,
  haulData,
}) => {
  const [isCreateMode, setIsCreateMode] = React.useState(!haulData);
  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 onSubmit = (values: FormValues) => {
    // Map form values to the FishingLogInfo-like shape the user requested
    const mapped = values.fish.map((f) => {
      const meta = fishSpecies!.find((x) => x.id === f.id);
      return {
        fish_species_id: f.id,
        fish_name: meta?.name,
        catch_number: f.quantity,
        catch_unit: f.unit,
        fish_size: f.size,
        fish_rarity: meta?.rarity_level,
        fish_condition: "",
        gear_usage: "",
      } as unknown; // inferred shape — keep as unknown to avoid relying on global types here
    });

    console.log("SUBMIT (FishingLogInfo[]): ", JSON.stringify(mapped, null, 2));

    // close modal after submit (you can change this to pass the payload to a parent via prop)
    onClose();
  };

  // 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);
      return;
    }

    // when modal opened, populate based on haulData
    if (haulData === null) {
      // explicit null -> start with a single default item
      reset({ fish: [defaultItem()] });
      setIsCreateMode(true);
    } else if (Array.isArray(haulData) && haulData.length > 0) {
      // map FishingLogInfo -> form rows
      const mapped = haulData.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,
      }));
      reset({ fish: mapped as any });
      setIsCreateMode(false);
    } else {
      // undefined or empty array -> default
      reset({ fish: [defaultItem()] });
      setIsCreateMode(true);
    }
  }, [isVisible, haulData, reset]);
  const renderRow = ({ item, index }: { item: any; index: number }) => {
    return (
      <View
        style={{
          marginBottom: 12,
          padding: 12,
          borderWidth: 1,
          borderRadius: 8,
        }}
      >
        <Text style={{ fontWeight: "600", marginBottom: 8 }}>
          Loài cá #{index + 1}
        </Text>

        {/* Species dropdown */}
        <Controller
          control={control}
          name={`fish.${index}.id`}
          render={({ field: { value, onChange } }) => (
            <View style={{ marginBottom: 8 }}>
              <Text style={{ marginBottom: 4 }}>Tên cá</Text>
              <Select
                options={fishSpecies!.map((fish) => ({
                  label: fish.name,
                  value: fish.id,
                }))}
                value={value}
                onChange={onChange}
                placeholder="Chọn loài cá"
              />
              {errors.fish?.[index]?.id && (
                <Text style={{ color: "red" }}>
                  {errors.fish[index]?.id?.message as string}
                </Text>
              )}
            </View>
          )}
        />

        {/* Quantity */}
        <Controller
          control={control}
          name={`fish.${index}.quantity`}
          render={({ field: { value, onChange, onBlur } }) => (
            <View style={{ marginBottom: 8 }}>
              <Text style={{ marginBottom: 4 }}>Số lượng</Text>
              <TextInput
                keyboardType="numeric"
                value={String(value ?? "")}
                onBlur={onBlur}
                onChangeText={(t) =>
                  onChange(Number(t.replace(/,/g, ".")) || 0)
                }
                style={{ padding: 10, borderWidth: 1, borderRadius: 6 }}
              />
              {errors.fish?.[index]?.quantity && (
                <Text style={{ color: "red" }}>
                  {errors.fish[index]?.quantity?.message as string}
                </Text>
              )}
            </View>
          )}
        />

        {/* Unit dropdown */}
        <Controller
          control={control}
          name={`fish.${index}.unit`}
          render={({ field: { value, onChange } }) => (
            <View style={{ marginBottom: 8 }}>
              <Text style={{ marginBottom: 4 }}>Đơn vị</Text>
              <Select
                options={UNITS_OPTIONS.map((unit) => ({
                  label: unit.label,
                  value: unit.value,
                }))}
                value={value}
                onChange={onChange}
                placeholder="Chọn đơn vị"
              />
              {errors.fish?.[index]?.unit && (
                <Text style={{ color: "red" }}>
                  {errors.fish[index]?.unit?.message as string}
                </Text>
              )}
            </View>
          )}
        />

        {/* Size (optional) */}
        <Controller
          control={control}
          name={`fish.${index}.size`}
          render={({ field: { value, onChange, onBlur } }) => (
            <View style={{ marginBottom: 8 }}>
              <Text style={{ marginBottom: 4 }}>
                Kích thước (cm) — tùy chọn
              </Text>
              <TextInput
                keyboardType="numeric"
                value={value ? String(value) : ""}
                onBlur={onBlur}
                onChangeText={(t) =>
                  onChange(t ? Number(t.replace(/,/g, ".")) : undefined)
                }
                style={{ padding: 10, borderWidth: 1, borderRadius: 6 }}
              />
              {errors.fish?.[index]?.size && (
                <Text style={{ color: "red" }}>
                  {errors.fish[index]?.size?.message as string}
                </Text>
              )}
            </View>
          )}
        />

        {/* Remove row */}
        <View style={{ flexDirection: "row", justifyContent: "flex-end" }}>
          <Button title="Xóa loài này" onPress={() => remove(index)} />
        </View>
      </View>
    );
  };

  return (
    <Modal
      visible={isVisible}
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <Text>{isCreateMode ? "Create Haul" : "Update Haul"}</Text>
      <FlatList
        data={fields}
        keyExtractor={(it) => it._id}
        renderItem={renderRow}
        ListFooterComponent={
          <View style={{ marginTop: 8 }}>
            <Button
              title="Thêm loài cá"
              onPress={() => append(defaultItem())}
            />
          </View>
        }
      />

      {errors.fish && (
        <Text style={{ color: "red", marginTop: 8 }}>
          {(errors.fish as any)?.message}
        </Text>
      )}

      <View style={{ marginTop: 16 }}>
        <Button title="Lưu thu hoạch" onPress={handleSubmit(onSubmit)} />
      </View>
    </Modal>
  );
};

export default CreateOrUpdateHaulModal;
