import { useState } from "react";
import {
  Box,
  TextField,
  MenuItem,
  Button,
  Drawer,
  FormControl,
  Select,
  Typography,
  Stack,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import SearchIcon from "@mui/icons-material/Search";
import RefreshIcon from "@mui/icons-material/Refresh";

const currencies = ["USD", "EUR", "GBP"];
const states = ["Pending", "Completed", "Failed"];
const transactionTypes = ["Credit", "Debit"];
const paymentMethods = ["Card", "Bank Transfer"];

export default function AdvancedSearch({setForm, form, resetForm}) {
  const [open, setOpen] = useState(false);

  const handleChange = (field: string, value: any) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const toggleDrawer =
    (open: boolean) => (event: React.KeyboardEvent | React.MouseEvent) => {
      if (
        event.type === "keydown" &&
        ((event as React.KeyboardEvent).key === "Tab" ||
          (event as React.KeyboardEvent).key === "Shift")
      ) {
        return;
      }

      setOpen(open);
    };

  const list = () => (
    <Box sx={{ width: 400 }} role="presentation">
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <Box p={2}>
          <Box sx={{ display: "flex", gap: "60px" }}>
            <Typography variant="h6" gutterBottom>
              Search
            </Typography>
            {/* Buttons */}
            <Box display="flex" justifyContent="flex-end" gap={2}>
              <Button
                variant="contained"
                startIcon={<SearchIcon />}
                onClick={() => console.log("Apply Filter", form)}
                sx={{ "& .span": { margin: "0px", padding: "0px" } }}
              >
                Apply Filter
              </Button>
              <Button
                variant="outlined"
                startIcon={<RefreshIcon sx={{ margin: "0px" }} />}
                onClick={resetForm}
                sx={{ "& span": { margin: "0px", padding: "0px" } }}
              ></Button>
            </Box>
          </Box>
          <Stack spacing={2}>
            {[
              { label: "Keyword", field: "keyword", type: "text" },
              { label: "Transaction ID", field: "transactionID", type: "text" },
              {
                label: "Transaction Reference ID",
                field: "transactionReferenceId",
                type: "text",
              },
              { label: "User", field: "user", type: "text" },
              {
                label: "Currency",
                field: "currency",
                type: "select",
                options: currencies,
              },
              {
                label: "State",
                field: "state",
                type: "select",
                options: states,
              },
              {
                label: "Status Description",
                field: "statusDescription",
                type: "text",
              },
              {
                label: "Transaction Type",
                field: "transactionType",
                type: "select",
                options: transactionTypes,
              },
              {
                label: "Payment Method",
                field: "paymentMethod",
                type: "select",
                options: paymentMethods,
              },
              { label: "PSPs", field: "psps", type: "text" },
              { label: "Initial PSPs", field: "initialPsps", type: "text" },
              { label: "Merchants", field: "merchants", type: "text" },
              { label: "Start Date", field: "startDate", type: "date" },
              { label: "End Date", field: "endDate", type: "date" },
              {
                label: "Last Updated From",
                field: "lastUpdatedFrom",
                type: "date",
              },
              {
                label: "Last Updated To",
                field: "lastUpdatedTo",
                type: "date",
              },
              { label: "Min Amount", field: "minAmount", type: "text" },
              { label: "Max Amount", field: "maxAmount", type: "text" },
              { label: "Channel", field: "channel", type: "text" },
            ].map(({ label, field, type, options }) => (
              <Box key={field}>
                <Typography variant="body2" fontWeight={600} mb={0.5}>
                  {label}
                </Typography>
                {type === "text" && (
                  <TextField
                    fullWidth
                    size="small"
                    value={form[field]}
                    onChange={(e) => handleChange(field, e.target.value)}
                  />
                )}
                {type === "select" && (
                  <FormControl fullWidth size="small">
                    <Select
                      value={form[field]}
                      onChange={(e) => handleChange(field, e.target.value)}
                      displayEmpty
                    >
                      <MenuItem value="">
                        <em>{label}</em>
                      </MenuItem>
                      {options.map((option) => (
                        <MenuItem value={option} key={option}>
                          {option}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
                {type === "date" && (
                  <DatePicker
                    value={form[field]}
                    onChange={(newValue) => handleChange(field, newValue)}
                    renderInput={(params) => (
                      <TextField fullWidth size="small" {...params} />
                    )}
                  />
                )}
              </Box>
            ))}
          </Stack>
        </Box>
      </LocalizationProvider>
    </Box>
  );
  return (
    <Box sx={{width: '185px'}}>
      <Button
        sx={{
          borderRadius: "8px",
          textTransform: "none",
          backgroundColor: "#f5f5f5",
          color: "#555",
          padding: "6px 12px",
          boxShadow: "inset 0 0 0 1px #ddd",
          fontWeight: 400,
          fontSize: "16px",
          justifyContent: "flex-start",
          "& .MuiButton-startIcon": {
            borderRadius: "4px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          },
          "&:hover": {
            backgroundColor: "#e0e0e0",
          },
        }}
        startIcon={<SearchIcon />}
        onClick={toggleDrawer(true)}
      >
        Advanced Search
      </Button>
      {/* <Button onClick={toggleDrawer(true)}>Open Right Drawer</Button> */}
      <Drawer anchor="right" open={open} onClose={toggleDrawer(false)}>
        {list()}
      </Drawer>
    </Box>
  );
}
