// resources/assets/ts/ContactsPage/components/NotizenDateiTab/AlleNotizenDatei.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 Stack from '@mui/material/Stack';
import Chip from '@mui/material/Chip';
import CircularProgress from '@mui/material/CircularProgress';
import Link from '@mui/material/Link';
import Collapse from '@mui/material/Collapse';
import {
  Description as FileIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Download as DownloadIcon,
  ExpandMore as ExpandMoreIcon,
} from '@mui/icons-material';
import NotizenDialog from './NotizenDialog';
import { getFileIcon, getFileExtension, getFileDownloadUrl } from './notizenDateiUtils';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface AlleNotizenDateiItem {
  type: 'notiz' | 'datei';
  id: string | number;
  timestamp: string;
  data: any;
}

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

const AlleNotizenDatei: React.FC<AlleNotizenDateiProps> = ({
  contactId,
  csrfToken,
  currentUser,
  refreshTrigger,
}) => {
  const { i18n } = useLingui();
  const [alleNotizenDatei, setAlleNotizenDatei] = useState<AlleNotizenDateiItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());


  const [editingNotiz, setEditingNotiz] = useState<any | null>(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);

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

  const fetchAlleNotizenDatei = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/contacts/getAlleNotizenDateiLatest/${contactId}`, {
        headers: { 'Accept': 'application/json' },
      });

      if (!response.ok) throw new Error('Failed to fetch AlleNotizenDatei');

      const data = await response.json();
      setAlleNotizenDatei(data.timeline || []); //  Changed from AlleNotizenDatei to timeline (backend response)
      // console.log(` Loaded ${data.total_items} items (${data.notizen_count} notizen, ${data.dateien_count} dateien)`);
    } finally {
      setLoading(false);
    }
  };

  const handleToggleExpand = (id: string) => {
    setExpandedIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  //  Handle edit
  const handleEdit = (notiz: any) => {
    setEditingNotiz(notiz);
    setEditDialogOpen(true);
  };

  //  Handle edit success
  const handleEditSuccess = () => {
    setEditDialogOpen(false);
    setEditingNotiz(null);
    fetchAlleNotizenDatei(); // Refresh the list
  };

  const handleDeleteNotiz = async (notizId: number) => {
    if (!window.confirm(i18n._(msg`Delete this note?`))) return;

    const formData = new FormData();
    formData.append('Ntzid', notizId.toString());
    formData.append('delNtz', '1');
    formData.append('_token', csrfToken);

    try {
      const response = await fetch('/contacts/saveNtz', {
        method: 'POST',
        body: formData,
        headers: { 'Accept': 'application/json' },
      });

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

      fetchAlleNotizenDatei();
    } catch (error) {
      console.error('Error deleting notiz:', error);
      alert(i18n._(msg`Error deleting the note`));
    }
  };

  const handleDeleteFile = async (filePath: string) => {
    if (!window.confirm(i18n._(msg`Delete this file?`))) return;

    const fileName = filePath.split('/').pop() || '';
    const formData = new FormData();
    formData.append('file', fileName);
    formData.append('Folder', 'none');
    formData.append('adr_id', contactId.toString());
    formData.append('_token', csrfToken);

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

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

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

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

  //  const getFileDownloadUrl = (item: AlleNotizenDateiItem): string => {
  //   if (item.type !== 'datei') return '#';

  //   const fullPath = item.data.path || item.data.name;
  //   const encodedPath = fullPath.split('/').map(encodeURIComponent).join('/');
  //   return `/crm/compfile/${contactId}/${encodedPath}`;
  // };

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

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

  return (
    <>
      <Stack spacing={2} sx={{ p: 2 }}>
        {alleNotizenDatei.map((item) => {
          const itemId = `${item.type}-${item.id}`;
          const isExpanded = expandedIds.has(itemId);
          const shouldShowExpand = item.type === 'notiz' && item.data.langtext && item.data.langtext.length > 100;

          return (
            <Card key={itemId}>
              <CardContent>
                {/* Header */}
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
                  <Box sx={{ flex: 1 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                      <Chip
                        label={item.type === 'notiz' ? i18n._(msg`Note`) : i18n._(msg`File`)}
                        size="small"
                        color={item.type === 'notiz' ? 'primary' : 'success'}
                      />
                      <Typography variant="caption" color="text.secondary">
                        {new Date(item.timestamp).toLocaleString('de-DE')}
                      </Typography>
                    </Box>

                    {item.type === 'notiz' ? (
                      <>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                          {getFileIcon('', 'notiz')}
                          <Typography variant="h3">
                            {item.data.beschreibung}
                          </Typography>
                        </Box>
                        <Typography variant="caption" color="text.secondary">
                          <Trans>Created by:</Trans> {item.data.bearbeiter}
                        </Typography>
                        {item.data.langtext && (
                          <Collapse
                            in={isExpanded || !shouldShowExpand}
                            collapsedSize={shouldShowExpand ? 60 : undefined}
                          >
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              sx={{
                                mt: 1,
                                whiteSpace: 'pre-wrap',
                                wordBreak: 'break-word',
                              }}
                            >
                              {item.data.langtext}
                            </Typography>
                          </Collapse>
                        )}
                      </>
                    ) : (
                      <>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                          {getFileIcon(item.data.name)}
                          <Link
                            href={getFileDownloadUrl(contactId, item.data.path || item.data.name)}
                            target="_blank"
                            rel="noopener noreferrer"
                            sx={{ fontWeight: 600 }}
                          >
                            {item.data.name}
                          </Link>
                        </Box>
                        <Typography variant="caption" color="text.secondary">
                          {item.data.size && i18n._(msg`Size: ${(item.data.size / 1024).toFixed(2)} KB`)}
                          {item.data.size && item.data.name && ' • '}
                          {item.data.name && getFileExtension(item.data.name)}
                        </Typography>
                      </>
                    )}
                  </Box>

                  {/* Action Buttons */}
                  <Box sx={{ display: 'flex', gap: 1 }}>
                    {item.type === 'notiz' ? (
                      <>
                        <IconButton
                          size="small"
                          onClick={() => handleEdit(item.data)} //  Use local handler
                          title={i18n._(msg`Edit`)}
                        >
                          <EditIcon fontSize="small" />
                        </IconButton>
                        <IconButton
                          size="small"
                          onClick={() => handleDeleteNotiz(item.data.notiz_id)}
                          color="error"
                          title={i18n._(msg`Delete`)}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                        {shouldShowExpand && (
                          <IconButton
                            size="small"
                            onClick={() => handleToggleExpand(itemId)}
                            sx={{
                              transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                              transition: '0.3s',
                            }}
                            title={isExpanded ? 'Weniger anzeigen' : 'Mehr anzeigen'}
                          >
                            <ExpandMoreIcon />
                          </IconButton>
                        )}
                      </>
                    ) : (
                      <>
                        <IconButton
                          size="small"
                          component="a"
                          href={getFileDownloadUrl(contactId, item.data.path || item.data.name)}
                          download
                          title={i18n._(msg`Download`)}
                        >
                          <DownloadIcon fontSize="small" />
                        </IconButton>
                        <IconButton
                          size="small"
                          onClick={() => handleDeleteFile(item.data.path)}
                          color="error"
                          title={i18n._(msg`Delete`)}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      </>
                    )}
                  </Box>
                </Box>
              </CardContent>
            </Card>
          );
        })}
      </Stack>

      {/*  Edit Dialog - self-contained */}
      {editingNotiz && (
        <NotizenDialog
          open={editDialogOpen}
          onClose={() => {
            setEditDialogOpen(false);
            setEditingNotiz(null);
          }}
          onSuccess={handleEditSuccess}
          contactId={contactId}
          csrfToken={csrfToken}
          currentUser={currentUser}
          editingNotiz={editingNotiz}
        />
      )}
    </>
  );
};

export default AlleNotizenDatei;
