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

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

export default function TransactionTable() {
  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 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: "",
    });
  };

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

  const handleExport = () => {
    const exportRows = onlyCurrentTable
      ? transactions.slice(0, 5)
      : transactions;
    const exportData = [
      columns.map((col) => col.headerName),
      ...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);
  };

  const [transactions, setTransactions] = useState<any[]>([]);

  const fetchTransactions = async () => {
    try {
      const query = new URLSearchParams(form as any).toString();
      const res = await fetch(`/api/transactions?${query}`);
      const data = await res.json();
      setTransactions(data);
    } catch (error) {
      console.error("Error fetching transactions:", error);
    }
  };

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

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

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

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

  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 }}
        />
        <AdvancedSearch form={form} resetForm={resetForm} setForm={setForm} />
        <SearchFilters
          filters={form}
          onDeleteFilter={handleDeleteFilter}
          onClearAll={handleClearAll}
        />
        {/* <RightTemporaryDrawer /> */}
        {/* <SearchFilterForm /> */}
        <Button
          variant="outlined"
          startIcon={<FileUploadIcon />}
          onClick={() => setOpen(true)}
        >
          Export
        </Button>
      </Stack>

      <DataGrid
        rows={transactions}
        columns={columns}
        initialState={{ pagination: { paginationModel } }}
        pageSizeOptions={[50, 100]}
        sx={{ border: 0, cursor: "pointer" }}
        onCellClick={(params, event) => {
          // Check if the click is on a specific column
          // Do something when this specific column is clicked
          handleClickField(params.field, params.value);
          console.log("Clicked cell value:", params.value); // The cell's value
          console.log("Column field:", params.field); // The column's field name (from your columns definition)
          console.log("Column header:", params.colDef.headerName); // The column's display name          // Your custom logic here
        }}
      />

      {/* 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",
}));
