import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Modal,
  TextField,
} from "@mui/material";
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Search } from '@mui/icons-material';
import './DirectorySearchModal.css';

interface DirectorySearchModalProps {
  dir: string;
  open: boolean;
  onClose: () => void;
  modalId: string;
}

interface FileData {
  id: number;
  filePath: string;
  fileName: string;
  fileExtension: string;
  createdAt: string;
  modifiedAt: string;
  accessedAt: string;
  size: number;
}

const columns: GridColDef[] = [
  { field: 'filePath', headerName: 'File Path', width: 250 },
  { field: 'fileName', headerName: 'File Name', width: 150 },
  { field: 'fileExtension', headerName: 'File Extension', width: 100 },
  {
    field: 'size',
    headerName: 'Size',
    width: 100,
    valueFormatter: (value:any) => {
      console.log("params.value:", value); // Debugging lin
      // Ensure the value is a number
      const bytes = typeof value === 'number' ? value : 0;

      if (bytes === 0) return '0 Bytes';

      const k = 1024;
      const dm = 2;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));

      return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
    },
  },
  { field: 'createdAt', headerName: 'Created At', width: 150 },
  { field: 'modifiedAt', headerName: 'Modified At', width: 150 },
  { field: 'accessedAt', headerName: 'Accessed At', width: 150 },
];



const DirectorySearchModal: React.FC<DirectorySearchModalProps> = ({ dir, open, onClose, modalId }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [rows, setRows] = useState<FileData[]>([]);

  useEffect(() => {
    handleSearchChange({ target: { value: '*' } } as any);
  }, []);

  const handleSearchChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const query = event.target.value;
    setSearchQuery(query);
    
    window.electron.meilisearchSearch(dir, query)
    .then((response: { success: boolean; data: any[]; error?: string }) => {
      if (response.success && response.data) {
        const fileData: FileData[] = response.data.map((doc: any, index: number) => ({
          id: doc.name,
          filePath: doc.name,
          fileName: doc.fileName,
          fileExtension: doc.extension,
          size: doc.size, // Ensure size is not undefined
          createdAt: doc.createdAt,
          modifiedAt: doc.modifiedAt,
          accessedAt: doc.accessedAt,
        }));
        setRows(fileData);
      } else {
        console.error('Error searching Meilisearch:', response.error);
        setRows([]);
      }
    });
  };

  return (
    <Modal
      id={modalId}
      open={open}
      onClose={onClose}
      aria-labelledby={`modal-title-${dir}`}
      aria-describedby={`modal-description-${dir}`}
    >
      <Box
        sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: '80%',
          maxWidth: 1200,
          bgcolor: "background.paper",
          boxShadow: 24,
          p: 4,
          borderRadius: 2,
        }}
      >
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            border: '1px solid white',
            borderRadius: '4px',
            paddingLeft: '8px',
            marginBottom: '8px',
          }}
        >
          <Search className="search-icon" sx={{ mr: 1, color: 'white' }} />
          <TextField
            placeholder={dir}
            variant="standard"
            fullWidth
            onChange={handleSearchChange}
            InputProps={{
              disableUnderline: true,
              style: {
                color: 'white',
              },
            }}
            sx={{
              '& .MuiInputBase-input': {
                color: 'white',
              },
            }}
          />
        </Box>
        <div style={{ height: 400, width: '100%' }}>
          <DataGrid
            rows={rows}
            columns={columns}
            checkboxSelection
            rowCount={rows.length}
          />
        </div>
        <Button
          variant="contained"
          color="primary"
          onClick={onClose}
          sx={{ mt: 2, m:1 }}
        >
          Close
        </Button>
        <Button
          variant="contained"
          color="warning"
          onClick={onClose}
          disabled
          sx={{ mt: 2, m:1 }}
        >
          Move To
        </Button>
        <Button
          variant="contained"
          color="warning"
          onClick={onClose}
          disabled
          sx={{ mt: 2, m:1 }}
        >
          Copy To
        </Button>
        <Button
          variant="contained"
          color="error"
          onClick={onClose}
          disabled
          sx={{ mt: 2, m:1 }}
        >
          Clean From System
        </Button>
      </Box>
    </Modal>
  );
};

export default DirectorySearchModal;
