"use client";
import { useCallback, useEffect, useState } from "react";
import {
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  Select,
  MenuItem,
  FormControlLabel,
  Checkbox,
  Stack,
  Paper,
  styled,
  TextField,
} from "@mui/material";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import { DataGrid } from "@mui/x-data-grid";
import { depositTransactionsColumns, Labels } from "./constants";
import AdvancedSearch1 from "../../AdvancedSearch/AdvancedSearch1";
import SearchFilters from "@/app/components/searchFilter/SearchFilters";
import { exportData } from "@/app/utils/exportData";
import { ITransaction } from "./types";

const paginationModel = { page: 0, pageSize: 50 };

export default function DepositsTransactionsTable() {
  const [form, setForm] = useState({
    userId: "",
    transactionId: "",
    transactionReferenceId: "",
    currency: "",
    state: "",
    depositMethod: "",
    dateTime: "",
  });

  const [open, setOpen] = useState(false);
  const [fileType, setFileType] = useState<"csv" | "xls" | "xlsx">("csv");
  const [onlyCurrentTable, setOnlyCurrentTable] = useState(false);
  const [transactions, setTransactions] = useState<ITransaction[]>([]);


  console.log(777, form)




  const fetchTransactions = useCallback(async () => {
    try {
      const stringForm: Record<string, string> = Object.fromEntries(
        Object.entries(form).map(([key, value]) => [key, value === null ? "" : String(value)])
      );
      const query = new URLSearchParams(stringForm).toString();
      const res = await fetch(`/api/transactions/deposit?${query}`);
      const data = await res.json();
      setTransactions(data);
    } catch (error) {
      console.error('Error fetching transactions:', error);
    }
  }, [form]);


  const resetForm = () => {
    setForm({
      userId: "",
      transactionId: "",
      transactionReferenceId: "",
      currency: "",
      state: "",
      depositMethod: "",
      dateTime: "",
    });
  };

  useEffect(() => {
    fetchTransactions();
  }, [form, fetchTransactions]);

  const handleDeleteFilter = (key: string) => {
    setForm((prev) => ({ ...prev, [key]: '' }));
  };

  const handleClearAll = () => {
    resetForm()
    fetchTransactions()
  };


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


  return (
    <StyledPaper>
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        p={2}
      >
        <TextField
          label="Search"
          variant="outlined"
          size="small"
          onChange={(e) => console.log(`setSearchQuery(${e.target.value})`)}
          sx={{ width: 300 }}
        />
        <AdvancedSearch1 form={form} resetForm={resetForm} setForm={setForm} labels={Labels} />
        <SearchFilters filters={form} onDeleteFilter={handleDeleteFilter} onClearAll={handleClearAll} />
        <Button
          variant="outlined"
          startIcon={<FileUploadIcon />}
          onClick={() => setOpen(true)}
        >
          Export
        </Button>
      </Stack>

      <DataGrid
        rows={transactions}
        columns={depositTransactionsColumns}
        initialState={{ pagination: { paginationModel } }}
        pageSizeOptions={[50, 100]}
        sx={{ border: 0, cursor: 'pointer' }}

        onCellClick={(params) => {
          handleClickField(params.field, params.value as string)
        }}
      />

      {/* Export Dialog */}
      <Dialog open={open} onClose={() => setOpen(false)}>
        <DialogTitle>Export Transactions</DialogTitle>
        <DialogContent>
          <FormControl fullWidth sx={{ mt: 2 }}>
            <Select
              value={fileType}
              onChange={(e) =>
                setFileType(e.target.value as "csv" | "xls" | "xlsx")
              }
            >
              <MenuItem value="csv">CSV</MenuItem>
              <MenuItem value="xls">XLS</MenuItem>
              <MenuItem value="xlsx">XLSX</MenuItem>
            </Select>
          </FormControl>
          <FormControlLabel
            control={
              <Checkbox
                checked={onlyCurrentTable}
                onChange={(e) => setOnlyCurrentTable(e.target.checked)}
              />
            }
            label="Only export the results in the current table"
            sx={{ mt: 2 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={() => exportData(transactions, depositTransactionsColumns, fileType, onlyCurrentTable, setOpen)}>
            Export
          </Button>
        </DialogActions>
      </Dialog>
    </StyledPaper>
  );
}

const StyledPaper = styled(Paper)(() => ({
  height: "90vh",
  width: "80vw"
}));
