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

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

interface IDepositProps {
  res: ITransaction
}

const TransactionsTable = ({ res }: IDepositProps) => {
  const {filteredTransactions, transactionsColumns, transactionsSearchLabels} = res;
  const router = useRouter()
  const searchParams = useSearchParams()


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

  const filters = Object.fromEntries(searchParams.entries());


  const handleClickField = (field: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set(field, value)
    router.push(`?${params.toString()}`)
    router.refresh()
  };


  return (
    <Paper>
      <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 }}
        />
        <AdvancedSearch labels={transactionsSearchLabels} />
        <SearchFilters filters={filters} />
        <Button
          variant="outlined"
          startIcon={<FileUploadIcon />}
          onClick={() => setOpen(true)}
        >
          Export
        </Button>
      </Stack>

      <DataGrid
        rows={filteredTransactions}
        columns={transactionsColumns}
        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(filteredTransactions as unknown as ITransaction[], transactionsColumns, fileType, onlyCurrentTable, setOpen)}>
            Export
          </Button>
        </DialogActions>
      </Dialog>
    </Paper>
  );
}

export default TransactionsTable
