"use client";
import { 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 * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import { DataGrid } from "@mui/x-data-grid";
import { columns } from "./constants";
import { rows } from "./mockData";

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

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

  const handleExport = () => {
    const exportRows = onlyCurrentTable ? rows.slice(0, 5) : rows;
    const exportData = [
      columns.map((col) => col.headerName),
      // @ts-expect-error - Dynamic field access from DataGrid columns
      ...exportRows.map((row) => columns.map((col) => row[col.field] ?? "")),
    ];

    const worksheet = XLSX.utils.aoa_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Transactions");

    if (fileType === "csv") {
      const csv = XLSX.utils.sheet_to_csv(worksheet);
      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      saveAs(blob, "transactions.csv");
    } else {
      XLSX.writeFile(workbook, `transactions.${fileType}`, {
        bookType: fileType,
      });
    }

    setOpen(false);
  };

  return (
    <StyledPaper>
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        p={2}
      >
        <TextField
          label="Search"
          variant="outlined"
          size="small"
          // value={'searchQuery'}
          onChange={(e) => console.log(`setSearchQuery(${e.target.value})`)}
          sx={{ width: 300 }}
        />
        <Button
          variant="outlined"
          startIcon={<FileUploadIcon />}
          onClick={() => setOpen(true)}
        >
          Export
        </Button>
      </Stack>

      <DataGrid
        rows={rows}
        columns={columns}
        initialState={{ pagination: { paginationModel } }}
        pageSizeOptions={[50, 100]}
        sx={{ border: 0 }}
      />

      {/* 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={handleExport}>
            Export
          </Button>
        </DialogActions>
      </Dialog>
    </StyledPaper>
  );
}

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