"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, GridColDef, GridRenderCellParams } 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";

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();
  };

  const handleStatusChange = (id: number, newStatus: string) => {
    setRows(
      rows.map((row) => (row.id === id ? { ...row, status: newStatus } : row)),
    );
  };

  const [rows, setRows] = useState(filteredTransactions);
  const getColumnsWithDropdown = (columns: GridColDef[]) => {
    return columns.map((col) => {
      if (col.field === "actions") {
        return {
          ...col,
          renderCell: (params: GridRenderCellParams) => {
            const row = filteredTransactions.find((r) => r.id === params.id);
            const options = row?.options;

            if (!options) return params.value;

            return (
              <Select
                value={params.value ?? row.status}
                onChange={(e) =>
                  handleStatusChange(params.id as number, e.target.value)
                }
                size="small"
                sx={{
                  width: "100%",
                  "& .MuiOutlinedInput-notchedOutline": { border: "none" },
                  "& .MuiSelect-select": { py: 0.5 },
                }}
                onClick={(e) => e.stopPropagation()} // Prevent row click when selecting
              >
                {options.map((option: { value: string; label: string }) => (
                  <MenuItem key={option.value} value={option.value}>
                    {option.label}
                  </MenuItem>
                ))}
              </Select>
            );
          },
        };
      }
      return col;
    });
  };

  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={getColumnsWithDropdown(transactionsColumns) as GridColDef[]}
        initialState={{
          pagination: { paginationModel: { pageSize: 50 } },
        }}
        pageSizeOptions={[50, 100]}
        sx={{
          border: 0,
          cursor: "pointer",
          "& .MuiDataGrid-cell": {
            py: 1,
          },
        }}
        onCellClick={(params) => {
          if (params.field !== "actions") {
            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;
