import * as React from 'react';
import {
  Container, Typography, List, ListItem, IconButton, TextField, Box, ListItemText, ListItemSecondaryAction, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Button
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import AddIcon from '@mui/icons-material/Add';
import { ContactsService } from '../../openapi';
import type { ContactPerson, ContactPersonCreate, ContactPersonUpdate } from '../models/ContactPerson';

const ContactsManager: React.FC = () => {
    const [contacts, setContacts] = React.useState<ContactPerson[]>([]);
    const [newContact, setNewContact] = React.useState<Partial<ContactPerson>>({
        firstname: '',
        lastname: '',
        phone_number: '',
        email: '',
    });
    const [editContactId, setEditContactId] = React.useState<number | null>(null);
    const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const [selectedContact, setSelectedContact] = React.useState<ContactPerson | null>(null);

    React.useEffect(() => {
        const fetchContacts = async () => {
            try {
                const response = await ContactsService.getContactsContactsGet();
                setContacts(response);
            } catch (error) {
                console.error('Failed to fetch contacts', error);
                setErrorMessage('Failed to load contacts. Please try again later.');
            }
        };

        fetchContacts();
    }, []);

    const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = event.target;
        setNewContact({ ...newContact, [name]: value });
    };

    const handleAddOrUpdateContact = async () => {
        try {
            if (editContactId !== null) {
                // Update contact
                await ContactsService.updateContactContactsContactIdPut(editContactId, newContact as ContactPersonUpdate);
                setContacts(contacts.map(contact => contact.id === editContactId ? { ...contact, ...newContact } : contact));
                setEditContactId(null);
            } else {
                // Add new contact
                const response = await ContactsService.createContactContactsPost(newContact as ContactPersonCreate);
                setContacts([...contacts, response]);
            }
            setNewContact({ firstname: '', lastname: '', phone_number: '', email: '' });
            setErrorMessage(null);
        } catch (error) {
            console.error('Failed to add/update contact', error);
            setErrorMessage('Failed to add/update contact. Please try again later.');
        }
    };

    const handleDeleteContact = async (id: number) => {
        try {
            await ContactsService.deleteContactContactsContactIdDelete(id);
            setContacts(contacts.filter(contact => contact.id !== id));
        } catch (error) {
            console.error('Failed to delete contact', error);
            setErrorMessage('Failed to delete contact. Please try again later.');
        }
    };

    const handleEditContact = (contact: ContactPerson) => {
        setEditContactId(contact.id);
        setNewContact(contact);
    };

    const openDialog = (contact: ContactPerson) => {
        setSelectedContact(contact);
        setDialogOpen(true);
    };

    const closeDialog = () => {
        setDialogOpen(false);
        setSelectedContact(null);
    };

    const confirmDelete = async () => {
        if (selectedContact) {
            await handleDeleteContact(selectedContact.id);
            closeDialog();
        }
    };

    return (
        <Container>
            <Typography variant="h4" gutterBottom>
                Contacts Management
            </Typography>
            <Box mb={3} display="flex" justifyContent="center" alignItems="center">
                <TextField label="First Name" name="firstname" value={newContact.firstname || ''} onChange={handleInputChange} />
                <TextField label="Last Name" name="lastname" value={newContact.lastname || ''} onChange={handleInputChange} />
                <TextField label="Phone Number" name="phone_number" value={newContact.phone_number || ''} onChange={handleInputChange} />
                <TextField label="Email" name="email" value={newContact.email || ''} onChange={handleInputChange} />
                <IconButton color="primary" onClick={handleAddOrUpdateContact}>
                    {editContactId !== null ? <SaveIcon /> : <AddIcon />}
                </IconButton>
            </Box>
            {errorMessage && <Typography color="error">{errorMessage}</Typography>}
            <List>
                {contacts.length > 0 ? (
                    contacts.map((contact) => (
                        <ListItem key={contact.id} button>
                            <ListItemText
                                primary={`${contact.firstname} ${contact.lastname}`}
                                secondary={`${contact.phone_number} - ${contact.email}`}
                            />
                            <ListItemSecondaryAction>
                                <IconButton edge="end" color="primary" onClick={() => handleEditContact(contact)}>
                                    <EditIcon />
                                </IconButton>
                                <IconButton edge="end" color="secondary" onClick={() => openDialog(contact)}>
                                    <DeleteIcon />
                                </IconButton>
                            </ListItemSecondaryAction>
                        </ListItem>
                    ))
                ) : (
                    <Typography>No contacts found</Typography>
                )}
            </List>
            <Dialog
                open={dialogOpen}
                onClose={closeDialog}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
            >
                <DialogTitle id="alert-dialog-title">{"Confirm Delete"}</DialogTitle>
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        Are you sure you want to delete this contact?
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={closeDialog} color="primary">
                        Cancel
                    </Button>
                    <Button onClick={confirmDelete} color="secondary" autoFocus>
                        Delete
                    </Button>
                </DialogActions>
            </Dialog>
        </Container>
    );
};

export default ContactsManager;