"use client";
import React, { useState, FC } from "react";
import {
  Stack,
  Typography,
  FormControlLabel,
  Checkbox,
  Autocomplete,
  Button,
  Grid,
  TextField,
  CardHeader,
  Card,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  ThemeProvider,
} from "@mui/material";
import { useForm, Controller } from "react-hook-form";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import SearchIcon from "@mui/icons-material/Search";
import RefreshIcon from "@mui/icons-material/Refresh";
import { DemoItem } from "@mui/x-date-pickers/internals/demo";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

interface Field {
  id: any;
  label: any;
  type: string;
  options?: Array<{ id: string; label: string }>;
  setValue: ((value: any) => void) | Array<(value: any) => void>;
  value?: any;
  required?: boolean;
}

interface FormComponentProps {
  fields: Field[];
  onSubmit: (data: any) => void;
  resetForm: () => void;
  sx?: any;
}

interface SearchFormProps {
  applySearch: (data: any) => void;
  fields: Field[];
  title?: string;
  sx?: any;
}

const FormComponent: FC<FormComponentProps> = ({
  fields,
  onSubmit,
  resetForm,
  sx,
}) => {
  const { reset, register, handleSubmit, control } = useForm();
  const [fromDate, setFromDate] = useState<dayjs.Dayjs | null>(null);
  const [dayRangeFromDate, setDayRangeFromDate] = useState<dayjs.Dayjs | null>(
    null,
  );
  const [dayRangeToDate, setDayRangeToDate] = useState<dayjs.Dayjs | null>(
    null,
  );
  const [value, setValue] = useState<{ [key: string]: any }>({});
  const [checkbox1, setCheckbox1] = useState(false);

  const handleFormSubmit = (data: any) => {
    if (fromDate != null || fromDate != undefined) {
      data.fromDate = dayjs(fromDate).format("YYYY-MM-DD");
    }
    if (value !== null) {
      data.dropdownCombo = value;
    }
    if (value !== null) {
      data.checkbox = checkbox1;
    }
    if (dayRangeFromDate != null || dayRangeFromDate != undefined) {
      data.dayRangeFromDate = dayjs(dayRangeFromDate).format("YYYY-MM-DD");
    }
    if (dayRangeToDate != null || dayRangeToDate != undefined) {
      data.dayRangeToDate = dayjs(dayRangeToDate).format("YYYY-MM-DD");
    }
    onSubmit(data);
  };

  const handleFormReset = () => {
    reset();
    resetForm();
    setFromDate(null);
    fields.forEach((field) => {
      if (typeof field.setValue === "function") {
        field.setValue(typeof field.value === "boolean" ? false : null);
      } else if (Array.isArray(field.setValue)) {
        field.setValue.forEach((setFunc) => {
          setFunc(null);
        });
      }
    });
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)}>
      <Grid container alignItems="center">
        {fields.map((field) => {
          if (field.type === "dropdown") {
            return (
              <Grid
                item
                xs={12}
                sm={5.5}
                md={5.5}
                lg={5.5}
                sx={{ ml: 3, mr: 3, mb: 3 }}
                key={field.id}
              >
                <FormControl fullWidth>
                  <InputLabel id={`${field.id}-label`}>
                    {field.label}
                  </InputLabel>
                  <Controller
                    name={field.id}
                    control={control}
                    defaultValue=""
                    render={({ field: { onChange, value } }) => (
                      <Select
                        labelId={`${field.id}-label`}
                        id={field.id}
                        value={value}
                        onChange={(e) => {
                          onChange(e.target.value);
                        }}
                      >
                        {field.options?.map((option) => (
                          <MenuItem
                            value={option.id ?? JSON.stringify(option)}
                            key={option.id ?? JSON.stringify(option)}
                          >
                            {option.id !== undefined
                              ? option.label
                              : JSON.stringify(option)}
                          </MenuItem>
                        ))}
                      </Select>
                    )}
                  />
                </FormControl>
              </Grid>
            );
          } else if (field.type === "date") {
            return (
              <Grid
                item
                xs={12}
                sm={5.5}
                md={5.5}
                lg={5.5}
                sx={{ ml: 3, mr: 3, mb: 3 }}
                key={field.id}
              >
                <LocalizationProvider dateAdapter={AdapterDayjs}>
                  <DemoItem>
                    <DatePicker
                      slotProps={{
                        textField: {
                          id: field.id,
                        },
                      }}
                      label={field.label}
                      value={fromDate === null ? null : dayjs(fromDate)}
                      onChange={(newValue) => {
                        setFromDate(newValue);
                      }}
                    />
                  </DemoItem>
                </LocalizationProvider>
              </Grid>
            );
          } else if (field.type === "checkbox") {
            return (
              <Grid
                item
                xs={12}
                sm={5.5}
                md={5.5}
                lg={5.5}
                sx={{ ml: 3, mr: 3, mb: 3 }}
                key={field.id}
              >
                <FormControlLabel
                  control={
                    <Checkbox
                      id={field.id}
                      checked={field.value}
                      onChange={(event) => {
                        if (typeof field.setValue === "function") {
                          field.setValue(event.target.checked);
                          setCheckbox1(event.target.checked);
                        }
                      }}
                      color="primary"
                    />
                  }
                  label={
                    <Typography style={{ fontSize: "1.15em" }}>
                      {field.label}
                    </Typography>
                  }
                />
              </Grid>
            );
          } else if (field.type === "dateRange") {
            return (
              <Grid container key={field.id[0]}>
                <Grid
                  item
                  xs={12}
                  sm={7}
                  md={7}
                  lg={7}
                  sx={{ ml: 3, mr: 3, mb: 3 }}
                >
                  <Grid container>
                    <Grid>
                      <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <DatePicker
                          label={field.label[0]}
                          value={field.value[0]}
                          onChange={(newValue) => setDayRangeFromDate(newValue)}
                        />
                      </LocalizationProvider>
                    </Grid>

                    <Grid
                      item
                      xs={1.5}
                      sm={1.5}
                      md={1.5}
                      lg={1.5}
                      sx={{
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                      }}
                    >
                      To
                    </Grid>

                    <Grid item xs={5.25} sm={5.25} md={5.25} lg={5.25}>
                      <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <DatePicker
                          label={field.label[1]}
                          value={field.value[1]}
                          onChange={(newValue) => setDayRangeToDate(newValue)}
                        />
                      </LocalizationProvider>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            );
          }
          return (
            <Grid
              item
              xs={12}
              sm={5.5}
              md={5.5}
              lg={5.5}
              sx={{ ml: 3, mr: 3, mb: 3 }}
              key={field.id}
            >
              <TextField
                fullWidth
                {...register(field.id)}
                id={field.id}
                label={field.label}
                defaultValue={
                  field.value !== undefined && field.value !== null
                    ? `${field.value}`
                    : ""
                }
                required={field.required === true ? field.required : false}
                sx={{ ...sx }}
                InputProps={{
                  style: {
                    borderRadius: "10px",
                  },
                }}
              />
            </Grid>
          );
        })}
      </Grid>
      <Grid
        container
        maxWidth="lg"
        justifyContent="space-between"
        style={{ marginTop: -20 }}
      >
        <Stack direction="row">
          <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
            <Button
              className="h-12 w-32"
              style={{
                backgroundColor: "#92c1e9",
                color: "white",
                fontSize: "1.15em",
                fontWeight: 100,
                borderRadius: 10,
              }}
              type="submit"
            >
              <SearchIcon />
              &nbsp;Search
            </Button>
          </Grid>
          <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
            <Button
              className="h-12 w-32"
              style={{
                backgroundColor: "#f890a5",
                color: "white",
                fontSize: "1.15em",
                fontWeight: 100,
                borderRadius: 10,
              }}
              onClick={handleFormReset}
            >
              <RefreshIcon />
              &nbsp;Reset
            </Button>
          </Grid>
        </Stack>
      </Grid>
    </form>
  );
};

const CustomSearchForm: FC<SearchFormProps> = ({
  applySearch,
  fields,
  title,
  sx,
}) => {
  const Title = title || "Searching Criteria";

  const handleSubmit = (data: any) => {
    if (applySearch) {
      applySearch(data);
    } else {
      console.log("applySearch function is null");
    }
  };

  const handleFormReset = () => {
    console.log("Form Reset");
  };

  return (
    <Card style={{ marginRight: 20 }}>
      <CardHeader
        className="text-slate-500 "
        style={{ marginTop: -5 }}
        title={Title}
      ></CardHeader>
      <FormComponent
        fields={fields}
        onSubmit={handleSubmit}
        resetForm={handleFormReset}
        sx={sx}
      />
    </Card>
  );
};

export default CustomSearchForm;
