"use client";
import {
  Autocomplete,
  Box,
  Button,
  Card,
  CardContent,
  FormControl,
  FormControlLabel,
  FormLabel,
  Grid,
  InputLabel,
  MenuItem,
  Radio,
  RadioGroup,
  Select,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import { Check, EditNote } from "@mui/icons-material";
import { Controller, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import InputDataGrid from "../InputDataGrid";

import { SyntheticEvent, useCallback, useEffect, useMemo, useState } from "react";
import { GridColDef, GridRowModel } from "@mui/x-data-grid";
import { InputDataGridProps, TableRow } from "../InputDataGrid/InputDataGrid";
import { TypeEnum } from "@/app/utils/typeEnum";
import { CreateItemInputs } from "@/app/api/settings/item/actions";
import { ItemQc } from "@/app/api/settings/item";
import { QcCategoryCombo, QcItemInfo } from "@/app/api/settings/qcCategory";
import { fetchQcItemsByCategoryId } from "@/app/api/settings/qcCategory/client";
import { WarehouseResult } from "@/app/api/warehouse";
import QcItemsList from "./QcItemsList";
type Props = {
  //   isEditMode: boolean;
  //   type: TypeEnum;
  isEditMode: boolean;
  // type: TypeEnum;
  defaultValues?: Partial<CreateItemInputs> | undefined;
  qcChecks?: ItemQc[];
  qcCategoryCombo: QcCategoryCombo[];
  warehouses: WarehouseResult[];
};

const ProductDetails: React.FC<Props> = ({ isEditMode, qcCategoryCombo, warehouses, defaultValues: initialDefaultValues }) => {
  const [qcItems, setQcItems] = useState<QcItemInfo[]>([]);
  const [qcItemsLoading, setQcItemsLoading] = useState(false);

  const {
    t,
    i18n: { language },
  } = useTranslation("items");

  const {
    register,
    formState: { errors, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    setError,
    clearErrors,
  } = useFormContext<CreateItemInputs>();
  // const typeColumns = useMemo<GridColDef[]>(
  //   () => [
  //     {
  //       field: "type",
  //       headerName: "type",
  //       flex: 1,
  //       editable: true,
  //     },
  //   ],
  //   []
  // );
  // const weightUnitColumns = useMemo<GridColDef[]>(
  //   () => [
  //     {
  //       field: "weightUnit",
  //       headerName: "Weight Unit",
  //       flex: 1,
  //       editable: true,
  //     },
  //     {
  //       field: "conversion",
  //       headerName: "conversion", // show base unit
  //       flex: 1,
  //       type: "number",
  //       editable: true,
  //     },
  //   ],
  //   []
  // );
  // const uomColumns = useMemo<GridColDef[]>(
  //   () => [
  //     {
  //       field: "uom",
  //       headerName: "uom",
  //       flex: 1,
  //       editable: true,
  //     },
  //   ],
  //   []
  // );

  // const validationTest = useCallback(
  //   (
  //     newRow: GridRowModel<TableRow<Partial<CreateItemInputs>, EntryError>>
  //   ): EntryError => {
  //     const error: EntryError = {};
  //     console.log(newRow);
  //     return Object.keys(error).length > 0 ? error : undefined;
  //   },
  //   []
  // );
  const handleAutoCompleteChange = useCallback((event: SyntheticEvent<Element, Event>, value: QcCategoryCombo, onChange: (...event: any[]) => void) => {
    onChange(value.id)
}, [])

  // Ensure LocationCode is set from defaultValues when component mounts
  useEffect(() => {
    if (initialDefaultValues?.LocationCode && !getValues("LocationCode")) {
      setValue("LocationCode", initialDefaultValues.LocationCode);
    }
  }, [initialDefaultValues, setValue, getValues]);

  // Watch qcCategoryId and fetch QC items when it changes
  const qcCategoryId = watch("qcCategoryId");
  
  useEffect(() => {
    const fetchItems = async () => {
      if (qcCategoryId) {
        setQcItemsLoading(true);
        try {
          const items = await fetchQcItemsByCategoryId(qcCategoryId);
          setQcItems(items);
        } catch (error) {
          console.error("Failed to fetch QC items:", error);
          setQcItems([]);
        } finally {
          setQcItemsLoading(false);
        }
      } else {
        setQcItems([]);
      }
    };
    
    fetchItems();
  }, [qcCategoryId]);

  return (
    <Card sx={{ display: "block" }}>
      <CardContent component={Stack} spacing={4}>
        <Box>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Product Details")}
          </Typography>
          <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
            <Grid item xs={6}>
              <TextField
                label={t("Name")}
                fullWidth
                disabled
                {...register("name", {
                  required: "name required!",
                })}
                error={Boolean(errors.name)}
                helperText={errors.name?.message}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={t("Code")}
                fullWidth
                disabled
                {...register("code", {
                  required: "code required!",
                })}
                error={Boolean(errors.code)}
                helperText={errors.code?.message}
              />
            </Grid>
            <Grid item xs={6}>
              <Controller
                control={control}
                name="type"
                rules={{
                  required: "type required!",
                }}
                render={({ field }) => (
                  <FormControl fullWidth error={Boolean(errors.type)}>
                    <InputLabel>{t("Type")}</InputLabel>
                    <Select
                      value={field.value || ""}
                      label={t("Type")}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                    >
                      <MenuItem value="fg">FG</MenuItem>
                      <MenuItem value="wip">WIP</MenuItem>
                      <MenuItem value="mat">MAT</MenuItem>
                      <MenuItem value="cmb">CMB</MenuItem>
                      <MenuItem value="nm">NM</MenuItem>
                    </Select>
                    {errors.type && (
                      <Typography variant="caption" color="error" sx={{ mt: 0.5, ml: 1.5 }}>
                        {errors.type.message}
                      </Typography>
                    )}
                  </FormControl>
                )}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={t("description")}
                fullWidth
                disabled
                {...register("description")}
              />
            </Grid>
            <Grid item xs={6}>
                <Controller
                  control={control}
                  name="qcCategoryId"
                  render={({ field }) => (
                    <Autocomplete
                      disableClearable
                      options={qcCategoryCombo}
                      defaultValue={qcCategoryCombo.find(qc => qc.id === field.value)}
                      onChange={(event, value) => {
                        handleAutoCompleteChange(event, value, field.onChange)
                      }}
                      onBlur={field.onBlur}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          variant="outlined"
                          label={t("Qc Category")}
                        />
                      )}
                    />
                  )}
                />
            </Grid>
            <Grid item xs={6}>
              <Controller
                control={control}
                name="qcType"
                render={({ field }) => (
                  <FormControl fullWidth>
                    <InputLabel>{t("QC Type")}</InputLabel>
                    <Select
                      value={field.value || ""}
                      label={t("QC Type")}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                    >
                      <MenuItem value="IPQC">{t("IPQC")}</MenuItem>
                      <MenuItem value="EPQC">{t("EPQC")}</MenuItem>
                    </Select>
                  </FormControl>
                )}
              />
            </Grid>
            <Grid item xs={6}>
              <Controller
                control={control}
                name="LocationCode"
                render={({ field }) => (
                  <Autocomplete
                    freeSolo
                    options={warehouses.map((w) => ({
                      label: `${w.code}`,
                      code: w.code,
                    }))}
                    getOptionLabel={(option) =>
                      typeof option === "string"
                        ? option
                        : option.label ?? option.code ?? ""
                    }
                    value={
                      warehouses
                        .map((w) => ({
                          label: `${w.code}`,
                          code: w.code,
                        }))
                        .find((opt) => opt.code === field.value) ||
                      (field.value
                        ? { label: field.value as string, code: field.value as string }
                        : null)
                    }
                    onChange={(_e, value) => {
                      if (typeof value === "string") {
                        field.onChange(value.trim() === "" ? undefined : value);
                      } else {
                        field.onChange(value?.code ? (value.code.trim() === "" ? undefined : value.code) : undefined);
                      }
                    }}
                    onInputChange={(_e, value) => {
                      // keep manual input synced - convert empty string to undefined
                      field.onChange(value.trim() === "" ? undefined : value);
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label={t("DefaultLocationCode")}
                        fullWidth
                        error={Boolean(errors.LocationCode)}
                        helperText={errors.LocationCode?.message}
                      />
                    )}
                  />
                )}
              />
            </Grid>
            <Grid item xs={12}>
              <FormControl component="fieldset">
                <FormLabel component="legend">{t("Special Type")}</FormLabel>
                <RadioGroup
                  row
                  value={
                    watch("isEgg") === true ? "isEgg" :
                    watch("isFee") === true ? "isFee" :
                    watch("isBag") === true ? "isBag" :
                    "none"
                  }
                  onChange={(e) => {
                    const value = e.target.value;
                    setValue("isEgg", value === "isEgg", { shouldValidate: true });
                    setValue("isFee", value === "isFee", { shouldValidate: true });
                    setValue("isBag", value === "isBag", { shouldValidate: true });
                  }}
                >
                  <FormControlLabel value="none" control={<Radio />} label={t("None")} />
                  <FormControlLabel value="isEgg" control={<Radio />} label={t("isEgg")} />
                  <FormControlLabel value="isFee" control={<Radio />} label={t("isFee")} />
                  <FormControlLabel value="isBag" control={<Radio />} label={t("isBag")} />
                </RadioGroup>
              </FormControl>
            </Grid>
            <Grid item xs={12}>
              <QcItemsList
                qcItems={qcItems}
                loading={qcItemsLoading}
                categorySelected={!!qcCategoryId}
              />
            </Grid>
            <Grid item xs={12}>
              <Stack
                direction="row"
                justifyContent="flex-end"
                spacing={2}
                sx={{ mt: 2 }}
              >
                <Button
                  name="submit"
                  variant="contained"
                  startIcon={<Check />}
                  type="submit"
                  //   disabled={submitDisabled}
                >
                  {isEditMode ? t("Save") : t("Confirm")}
                </Button>
              </Stack>
            </Grid>
            {/* <Grid item xs={6}>
              <InputDataGrid<CreateItemInputs, EntryError>
                _formKey={"type"}
                columns={typeColumns}
                validateRow={validationTest}
              />
            </Grid>
            <Grid item xs={6}>
              <InputDataGrid<CreateItemInputs, EntryError>
                _formKey={"uom"}
                columns={uomColumns}
                validateRow={validationTest}
              />
            </Grid>
            <Grid item xs={12}>
              <InputDataGrid<CreateItemInputs, EntryError>
                _formKey={"weightUnit"}
                columns={weightUnitColumns}
                validateRow={validationTest}
              />
            </Grid>*/}
          </Grid>
        </Box>
      </CardContent>
    </Card>
  );
};
export default ProductDetails;
