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

interface Notiz {
  notiz_id: number;
  ntz_timestamp: string;
  Mitarbeiter: string;
  bearbeiter: string;
  beschreibung: string;
  langtext: string;
}

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

const NotizenList: React.FC<NotizenListProps> = ({
  contactId,
  csrfToken,
  currentUser,
  refreshTrigger,
}) => {
  const { i18n } = useLingui();
  const [notizen, setNotizen] = useState<Notiz[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
  const [editingNotiz, setEditingNotiz] = useState<Notiz | null>(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);

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

  const fetchNotizen = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/contacts/getadr/${contactId}`, {
        headers: { 'Accept': 'application/json' },
      });
      
      if (!response.ok) throw new Error('Failed to fetch');
      
      const data = await response.json();
      setNotizen(data.comments || []);
    } catch (error) {
      console.error('Error fetching notizen:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleEdit = (notiz: Notiz) => {
    setEditingNotiz(notiz);
    setEditDialogOpen(true);
  };

  const handleDelete = async (notiz: Notiz) => {
    if (!window.confirm(i18n._(msg`Delete this note?`))) return;

    const formData = new FormData();
    formData.append('Ntzid', notiz.notiz_id.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`));

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

  const handleEditSuccess = () => {
    setEditDialogOpen(false);
    setEditingNotiz(null);
    fetchNotizen();
  };

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

  if (notizen.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</Trans>
                </Typography>
                <Typography variant="body2" color="text.secondary">
                 <Trans>Click "+ Add" to create a new note.</Trans>
                </Typography>
              </Box>
    );
  }

  return (
    <>
      <Stack spacing={4} sx={{ p: 4 }}>
        {notizen.map((notiz) => {
          const isExpanded = expandedIds.has(notiz.notiz_id);
          const shouldShowExpand = notiz.langtext && notiz.langtext.length > 100;

         return (
            <Card key={notiz.notiz_id}>
              <CardContent>
                {/* Header Section */}
                <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 }}>
                      {getFileIcon('', 'notiz')}
                      <Typography variant="caption" color="text.secondary">
                        {new Date(notiz.ntz_timestamp).toLocaleString('de-DE')}
                      </Typography>
                    </Box>
                    <Typography variant="h3">
                      {notiz.beschreibung}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      <Trans>Created by:</Trans> {notiz.bearbeiter}
                    </Typography>
                    {notiz.langtext && (
                      <Collapse in={isExpanded || !shouldShowExpand} collapsedSize={shouldShowExpand ? 60 : undefined}>
                        <Typography
                          variant="body2"
                          color="text.secondary"
                          sx={{
                            mt: 1,
                            whiteSpace: 'pre-wrap',
                            wordBreak: 'break-word',
                          }}
                        >
                          {notiz.langtext}
                        </Typography>
                      </Collapse>
                    )}
                  </Box>

                  {/* Action Buttons */}
                  <Box sx={{ display: 'flex', gap: 1 }}>
                    <IconButton
                      size="small"
                      onClick={() => handleEdit(notiz)}
                      title={i18n._(msg`Edit`)}
                      aria-label={i18n._(msg`Edit`)}
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDelete(notiz)}
                      color="error"
                      title={i18n._(msg`Delete`)}
                      aria-label={i18n._(msg`Delete`)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                    {shouldShowExpand && (
                      <IconButton
                        size="small"
                        onClick={() => handleToggleExpand(notiz.notiz_id)}
                        sx={{
                          transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                          transition: '0.3s',
                        }}
                        title={isExpanded ? i18n._(msg`Show less`) : i18n._(msg`Show more`)}
                      >
                        <ExpandMoreIcon />
                      </IconButton>
                    )}
                  </Box>
                </Box>
              </CardContent>
            </Card>
          );
        })}
      </Stack>

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

export default NotizenList;
