import { Criterion } from "@/components/SearchBox/SearchBox";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { Card, CardContent, Typography, Grid, TextField, Button, Stack } from "@mui/material";
import { RestartAlt, Search } from "@mui/icons-material";
import { Autocomplete } from "@mui/material";

const VerticalSearchBox = ({ criteria, onSearch, onReset }: {
  criteria: Criterion<any>[];
  onSearch: (inputs: Record<string, any>) => void;
  onReset?: () => void;
}) => {
  const { t } = useTranslation("common");
  const [inputs, setInputs] = useState<Record<string, any>>({});

  const handleInputChange = (paramName: string, value: any) => {
    setInputs(prev => ({ ...prev, [paramName]: value }));
  };

  const handleSearch = () => {
    onSearch(inputs);
  };

  const handleReset = () => {
    setInputs({});
    onReset?.();
  };

  return (
    <Card>
      <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
        <Typography variant="overline">{t("Search Criteria")}</Typography>
        <Grid container spacing={2} columns={{ xs: 12, sm: 12 }}>
          {criteria.map((c) => {
            return (
              <Grid key={c.paramName} item xs={12}>
                {c.type === "text" && (
                  <TextField
                    label={t(c.label)}
                    fullWidth
                    onChange={(e) => handleInputChange(c.paramName, e.target.value)}
                    value={inputs[c.paramName] || ""}
                  />
                )}
                {c.type === "autocomplete" && (
                  <Autocomplete
                    options={c.options || []}
                    getOptionLabel={(option: any) => option.label}
                    onChange={(_, value: any) => handleInputChange(c.paramName, value?.value || "")}
                    value={c.options?.find(option => option.value === inputs[c.paramName]) || null}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label={t(c.label)}
                        fullWidth
                      />
                    )}
                  />
                )}
              </Grid>
            );
          })}
        </Grid>
        <Stack direction="row" spacing={2} sx={{ mt: 2 }}>
          <Button
            variant="text"
            startIcon={<RestartAlt />}
            onClick={handleReset}
          >
            {t("Reset")}
          </Button>
          <Button
            variant="outlined"
            startIcon={<Search />}
            onClick={handleSearch}
          >
            {t("Search")}
          </Button>
        </Stack>
      </CardContent>
    </Card>
  );
};

export default VerticalSearchBox;