// resources/assets/ts/ContactsPage/components/NotizenDateiTab/DateiList.tsx

import React, { useState, useEffect } from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';
import Stack from '@mui/material/Stack';
import Chip from '@mui/material/Chip';
import Link from '@mui/material/Link';
import {
  Download as DownloadIcon,
  Delete as DeleteIcon,
  Folder as FolderIcon,
  InsertDriveFile as FileIcon,
  Image as ImageIcon,
  PictureAsPdf as PdfIcon,
  Description as DocumentIcon,
} from '@mui/icons-material';
import { getFileIcon, getFileExtension, getFileDownloadUrl } from './notizenDateiUtils';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface DateiListProps {
  contactId: number;
  csrfToken: string;
  currentUser: string;
  refreshTrigger: number;
}

interface FileItem {
  path?: string;
  name: string;
  type: 'file' | 'directory';
  isFile: boolean;
  extension?: string;
  size?: number;
  timestamp?: string;
}

const DateiList: React.FC<DateiListProps> = ({
  contactId,
  csrfToken,
  refreshTrigger,
}) => {
  const { i18n } = useLingui();
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [folderPath, setFolderPath] = useState<string>('none');

  useEffect(() => {
    fetchFiles();
  }, [contactId, refreshTrigger, folderPath]);

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const serverPath = folderPath === 'none' ? 'none' : folderPath.replace(/\//g, ',');
      const response = await fetch(`/crm/folderFiles/${contactId}/${serverPath}`);
      const data: FileItem[] = await response.json();
      setFiles(data || []);
    } catch (error) {
      console.error('Error fetching files:', error);
      setFiles([]);
    } finally {
      setLoading(false);
    }
  };

  // Helper to get appropriate icon for file type
  // const getFileIcon = (fileName: string) => {
  //   const ext = fileName.split('.').pop()?.toLowerCase();

  //   if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext || '')) {
  //     return <ImageIcon color="action" />;
  //   } else if (ext === 'pdf') {
  //     return <PdfIcon color="action" />;
  //   } else if (['doc', 'docx', 'txt', 'odt'].includes(ext || '')) {
  //     return <DocumentIcon color="action" />;
  //   } else if (!fileName.includes('.')) {
  //     return <FolderIcon color="primary" />;
  //   } else {
  //     return <FileIcon color="action" />;
  //   }
  // };

  // Helper to extract file extension
  // const getFileExtension = (fileName: string): string => {
  //   const parts = fileName.split('.');
  //   return parts.length > 1 ? parts.pop()!.toUpperCase() : 'ORDNER';
  // };

  //  Helper function to build correct download URL
  // const getFileDownloadUrl = (file: FileItem): string => {
  //   const fullPath = file.path || file.name;  //fallback use filename if path missing from backend
  //   const encodedPath = fullPath.split('/').map(encodeURIComponent).join('/');
  //   return `/crm/compfile/${contactId}/${encodedPath}`;
  // };

  const handleFolderClick = (folderPath: string) => {
    setFolderPath(folderPath);
  };

  const handleDelete = async (file: FileItem, event?: React.MouseEvent) => {
    if (event) {
      event.stopPropagation();
    }

    const confirmMsg = file.isFile
      ? i18n._(msg`Really delete the file "${file.name}"?`)
      : i18n._(msg`Really delete the folder "${file.name}"?`);
    if (!window.confirm(confirmMsg)) {
      return;
    }

    const formData = new FormData();
    formData.append(file.isFile ? 'file' : 'name', file.name);
    formData.append('Folder', 'none');
    formData.append('adr_id', contactId.toString());
    formData.append('_token', csrfToken);

    const url = file.isFile ? '/crmFolder/deleteFile' : '/crmFolder/delFolder';

    try {
      const response = await fetch(url, {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) throw new Error(i18n._(msg`Error deleting`));

      fetchFiles();
    } catch (error) {
      console.error('Error deleting file:', error);
      alert(i18n._(msg`Error deleting`));
    }
  };

  const handleBackToRoot = () => {
    setFolderPath('none');
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (files.length === 0 && folderPath === 'none') {
    return (
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          mt: 12,
          height: '100%',
          gap: 2,
        }}
      >
        <Typography variant="h3" color="text.secondary">
          <Trans>No files</Trans>
        </Typography>
        <Typography variant="body2" color="text.secondary">
          <Trans>Click "+ Add" to upload files.</Trans>
        </Typography>
      </Box>
    );
  }


  return (
    <Box sx={{ p: 2 }}>
      {/* Back button when inside a folder */}
      {folderPath !== 'none' && (
        <Box sx={{ mb: 2 }}>
          <Chip
            icon={<FolderIcon />}
            label={i18n._(msg`Back to main folder`)}
            onClick={handleBackToRoot}
            clickable
            color="primary"
            variant="outlined"
          />
        </Box>
      )}

      <Stack spacing={2}>
        {files.map((file, index) => {
          const ext = file.extension || getFileExtension(file.name);
          const downloadUrl = file.isFile ? getFileDownloadUrl(contactId, file.path || file.name) : null;

          return (
            <Card
              key={index}
              onClick={() => !file.isFile && handleFolderClick(file.path)}
              sx={!file.isFile ? { cursor: 'pointer' } : undefined}
            >
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  {/* File/Folder Info */}
                  <Box sx={{ flex: 1 }}>
                    {file.timestamp && (
                      <Typography variant="caption" color="text.secondary" display="block" sx={{ mb: 1 }}>
                        {new Date(file.timestamp).toLocaleString('de-DE')}
                      </Typography>
                    )}
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                      {getFileIcon(file.name)}
                      {file.isFile ? (
                        <Link
                          href={downloadUrl!}
                          target="_blank"
                          rel="noopener noreferrer"
                          sx={{ fontWeight: 600 }}
                        >
                          {file.name}
                        </Link>
                      ) : (
                        <Typography variant="body1" sx={{ fontWeight: 600 }}>
                          {file.name}
                        </Typography>
                      )}
                    </Box>
                    <Typography variant="caption" color="text.secondary">
                      {file.isFile
                        ? `${file.size ? i18n._(msg`Size: ${(file.size / 1024).toFixed(2)} KB`) : ''}${file.size && ext ? ' • ' : ''}${ext}`
                        : i18n._(msg`Folder`)}
                    </Typography>
                  </Box>

                  {/* Action Buttons */}
                  <Box sx={{ display: 'flex', gap: 1 }}>
                    {file.isFile && (
                      <IconButton
                        size="small"
                        component="a"
                        href={downloadUrl!}
                        download
                        title={i18n._(msg`Download`)}
                        onClick={(e) => e.stopPropagation()}
                      >
                        <DownloadIcon fontSize="small" />
                      </IconButton>
                    )}
                    <IconButton
                      size="small"
                      onClick={(e) => handleDelete(file, e)}
                      color="error"
                      title={i18n._(msg`Delete`)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          );
        })}
      </Stack>
    </Box>
  )
};

export default DateiList;
