import Select from "@/components/Select";
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 { errors } = formState;

  const { fields, append, remove } = useFieldArray({
    control,
    name: "fish",
    keyName: "_id", // tránh đụng key
  });

  const onSubmit = (values: FormValues) => {
    console.log("SUBMIT: ", JSON.stringify(values, null, 2));
  };

  // 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={fishesExampleData.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;

const fishesExampleData = [
  {
    id: 1,
    name: "Cá thu",
    scientific_name: "Scomberomorus spp.",
    group_name: "Cá nổi",
    species_code: "TUNA01",
    note: "Loài phổ biến ở biển ven bờ và xa bờ",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 2,
    name: "Cá nục",
    scientific_name: "Decapterus spp.",
    group_name: "Cá nổi",
    species_code: "MACK01",
    note: "Loài cá thương mại nhỏ",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 3,
    name: "Cá chim trắng",
    scientific_name: "Pampus argenteus",
    group_name: "Cá nổi",
    species_code: "POMF01",
    note: "Thịt ngon, giá trị kinh tế cao",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 4,
    name: "Cá bống tượng",
    scientific_name: "Oxyeleotris marmorata",
    group_name: "Cá đáy",
    species_code: "GOBY01",
    note: "Cá đáy nước ngọt và lợ",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 5,
    name: "Cá mú đỏ",
    scientific_name: "Epinephelus malabaricus",
    group_name: "Nhóm mú",
    species_code: "GROUP01",
    note: "Cá mú đỏ phổ biến tại các rạn san hô",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 6,
    name: "Cá mú trắng",
    scientific_name: "Epinephelus fuscoguttatus",
    group_name: "Nhóm mú",
    species_code: "GROUP02",
    note: "Cá mú trắng rạn san hô",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 8,
    name: "Cá hồng phớn",
    scientific_name: "Nemipterus virgatus",
    group_name: "Cá đáy",
    species_code: "BREAM01",
    note: "Golden threadfin bream, rất phổ biến",
    default_unit: "kg",
    rarity_level: 3,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 9,
    name: "Cá hổ Napoleon",
    scientific_name: "Cheilinus undulatus",
    group_name: "Rạn san hô",
    species_code: "WRASSE01",
    note: "Humphead wrasse, loài nguy cấp được bảo vệ",
    default_unit: "kg",
    rarity_level: 4,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 10,
    name: "Cá quỷ biển (Barracuda)",
    scientific_name: "Sphyraena barracuda",
    group_name: "Cá săn mồi",
    species_code: "BARRA01",
    note: "Loài cá săn mồi nhanh",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 11,
    name: "Cá ngừ đại dương",
    scientific_name: "Thunnus albacares",
    group_name: "Cá nổi xa bờ",
    species_code: "TUNA02",
    note: "Tuna phổ biến vùng biển xa",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 12,
    name: "Cá nục vằn",
    scientific_name: "Scomberomorus commerson",
    group_name: "Cá nổi",
    species_code: "MACK02",
    note: "Mackerel phổ biến ở biển miền Trung",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 13,
    name: "Cá song đỏ",
    scientific_name: "Lutjanus argentimaculatus",
    group_name: "Cá đáy",
    species_code: "SNAPPER01",
    note: "Mangrove red snapper, giá trị kinh tế cao",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 14,
    name: "Cá mú cườm",
    scientific_name: "Epinephelus coioides",
    group_name: "Nhóm mú",
    species_code: "GROUP03",
    note: "Brown-spotted grouper, phổ biến ở vùng biển",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 15,
    name: "Cá hồng",
    scientific_name: "Lutjanus malabaricus",
    group_name: "Cá đáy",
    species_code: "SNAPPER02",
    note: "Malabar red snapper",
    default_unit: "kg",
    rarity_level: 2,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 16,
    name: "Cá rồng biển",
    scientific_name: "Choerodon schoenleinii",
    group_name: "Rạn san hô",
    species_code: "DRAGON01",
    note: "Cá rồng biển, cá cảnh hiếm",
    default_unit: "kg",
    rarity_level: 3,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 17,
    name: "Cá nược",
    scientific_name: "Pomatomus saltatrix",
    group_name: "Cá nổi",
    species_code: "QUEEN01",
    note: "Bluefish phổ biến",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 18,
    name: "Cá đuối quạt",
    scientific_name: "Platyrhina sinensis",
    group_name: "Cá mó",
    species_code: "RAY01",
    note: "Fanray, loài đe dọa",
    default_unit: "kg",
    rarity_level: 4,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 19,
    name: "Cá hổ Thái Lan",
    scientific_name: "Datnioides pulcher",
    group_name: "Cá nước lợ",
    species_code: "TIGER01",
    note: "Siamese tigerfish, nguy cấp",
    default_unit: "kg",
    rarity_level: 4,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 20,
    name: "Cá bớp vây vàng",
    scientific_name: "Taractes rubescens",
    group_name: "Cá nổi xa bờ",
    species_code: "POMF02",
    note: "Loài cá biển sâu ít gặp",
    default_unit: "kg",
    rarity_level: 3,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-08-29T06:34:38.785313Z",
    is_deleted: false,
  },
  {
    id: 43,
    name: "Cá Min Mon",
    scientific_name: "Minhmon",
    group_name: "Cá béo",
    species_code: "Caminhmon",
    note: "Cá béo nước cạn",
    default_unit: "tạ",
    rarity_level: 1,
    created_at: "2025-10-01T03:09:59.642716Z",
    updated_at: "2025-10-01T03:10:30.977697Z",
    is_deleted: true,
  },
  {
    id: 7,
    name: "Cá bơn vàng",
    scientific_name: "Cynoglossus robustus",
    group_name: "Cá đáy",
    species_code: "SOLE01",
    note: "Cá bơn đáy cát",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-08-29T06:34:38.785313Z",
    updated_at: "2025-10-01T03:10:39.927546Z",
    is_deleted: false,
  },
  {
    id: 22,
    name: "Cá mập",
    scientific_name: "Carcharodon",
    group_name: "Cá đáy",
    species_code: "Carcharodon",
    note: "Cá trắng",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-09-25T11:02:20.705804Z",
    updated_at: "2025-10-01T03:11:13.631101Z",
    is_deleted: true,
  },
  {
    id: 28,
    name: "cá cơm",
    scientific_name: "cá cơm",
    group_name: "cá cơm",
    species_code: "cacom",
    note: "no cmt",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-09-30T07:35:04.623573Z",
    updated_at: "2025-09-30T08:06:18.651249Z",
    is_deleted: true,
  },
  {
    id: 29,
    name: "cá minh mon",
    scientific_name: "cá min mon",
    group_name: "1",
    species_code: "cá min mon",
    note: "no",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-09-30T07:36:04.908601Z",
    updated_at: "2025-09-30T08:09:34.361879Z",
    is_deleted: true,
  },
  {
    id: 42,
    name: "cá mập",
    scientific_name: "camap",
    group_name: "cá đáy",
    species_code: "camap",
    note: "no",
    default_unit: "kg",
    rarity_level: 1,
    created_at: "2025-09-30T08:38:14.151734Z",
    updated_at: "2025-10-01T03:08:13.025517Z",
    is_deleted: true,
  },
];
