import React, { useState } from "react";
import {
  Box,
  Grid,
  TextField,
  MenuItem,
  Button,
  InputLabel,
  FormControl,
  Select,
  Typography,
} 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"];
const psps = ["Stripe", "PayPal"];
const merchants = ["Amazon", "eBay"];

export default function SearchFilterForm() {
  const [form, setForm] = useState({
    keyword: "",
    transactionId: "",
    transactionReferenceId: "",
    user: "",
    currency: "",
    state: "",
    statusDescription: "",
    transactionType: "",
    paymentMethod: "",
    psps: "",
    initialPsps: "",
    merchants: "",
    startDate: null,
    endDate: null,
    lastUpdatedFrom: null,
    lastUpdatedTo: null,
    minAmount: "",
    maxAmount: "",
    channel: "",
  });

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

  const resetForm = () => {
    setForm({
      keyword: "",
      transactionId: "",
      transactionReferenceId: "",
      user: "",
      currency: "",
      state: "",
      statusDescription: "",
      transactionType: "",
      paymentMethod: "",
      psps: "",
      initialPsps: "",
      merchants: "",
      startDate: null,
      endDate: null,
      lastUpdatedFrom: null,
      lastUpdatedTo: null,
      minAmount: "",
      maxAmount: "",
      channel: "",
    });
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Box p={2}>
        <Typography variant="h6" gutterBottom>
          Search
        </Typography>

        <Grid container 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 }) => (
            <Grid
              container
              item
              xs={12}
              alignItems="center"
              spacing={1}
              key={field}
            >
              <Grid item xs={4}>
                <Typography variant="body2" fontWeight={600}>
                  {label}
                </Typography>
              </Grid>
              <Grid item xs={8}>
                {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} />
                    )}
                  />
                )}
              </Grid>
            </Grid>
          ))}

          {/* Buttons */}
          <Grid item xs={12} display="flex" justifyContent="flex-end" gap={2}>
            <Button
              variant="outlined"
              startIcon={<RefreshIcon />}
              onClick={resetForm}
            >
              Reset
            </Button>
            <Button
              variant="contained"
              startIcon={<SearchIcon />}
              onClick={() => console.log("Apply Filter", form)}
            >
              Apply Filter
            </Button>
          </Grid>
        </Grid>
      </Box>
    </LocalizationProvider>
  );
}
