import SectionContainer from '../../components/SectionContainer.jsx';
import { useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { Typography, Button, Dialog, DialogTitle, DialogContent, IconButton, Box, Avatar } from '@mui/material';
import AddOrEditClientsForm from './AddOrEditClientsForm.jsx';

import EditRoundedIcon from '@mui/icons-material/EditRounded';
import DeleteRoundedIcon from '@mui/icons-material/DeleteRounded';
import '../../App.css';

export default function Clients() {
  const [rows, setRows] = useState([
    {
      id: 1,
      avatar: '/c2.jpg',
      fullName: 'Anna Wintour',
      email: 'anna@fendi.com',
      phone: '+1 555-1234',
      address: '123 Fashion Blvd, NY',
      company: 'Fendi Casa'
    },
    {
      id: 2,
      avatar: '/c3.jpg',
      fullName: 'Karl Lagerfeld',
      email: 'karl@fendi.com',
      phone: '+1 555-5678',
      address: '456 Style Ave, Paris',
      company: 'Fendi Casa'
    },
    {
      id: 3,
      avatar: '/c4.jpg',
      fullName: 'Donatella Versace',
      email: 'donatella@fendi.com',
      phone: '+1 555-9999',
      address: '789 Couture St, Milan',
      company: 'Fendi Casa'
    },
    {
      id: 4,
      avatar: '/c5.jpg',
      fullName: 'Giorgio Armani',
      email: 'giorgio@fendi.com',
      phone: '+1 555-8888',
      address: '101 Luxury Rd, Milan',
      company: 'Fendi Casa'
    }
  ]);

  const [open, setOpen] = useState(false);
  const [editingClient, setEditingClient] = useState(null);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [rowToDelete, setRowToDelete] = useState(null);

  const handleAddOrEditClient = (client) => {
    if (editingClient) {
      // Update existing
      setRows(rows.map((row) => (row.id === editingClient.id ? { ...editingClient, ...client } : row)));
    } else {
      // Add new
      const id = rows.length + 1;
      setRows([...rows, { id, company: 'Fendi casa', ...client }]);
    }
    setOpen(false);
    setEditingClient(null);
  };

  const handleEditClick = (params) => {
    setEditingClient(params.row);
    setOpen(true);
  };

  const handleDeleteClick = (row) => {
    setRowToDelete(row);
    setConfirmOpen(true);
  };

  const confirmDelete = () => {
    setRows(rows.filter((row) => row.id !== rowToDelete.id));
    setRowToDelete(null);
    setConfirmOpen(false);
  };

  const columns = [
    {
      field: 'avatar',
      headerName: '',
      width: 100,
      renderCell: (params) => (
        <Avatar
          src={params.value || '/favicon.png'}
          sx={{ width: 48, height: 48 }}
        />
      )
    },
    { field: 'fullName', headerName: 'Full Name', flex: 1 },
    { field: 'email', headerName: 'Email', flex: 1.5 },
    { field: 'phone', headerName: 'Phone', flex: 1 },
    { field: 'address', headerName: 'Address', flex: 1.5 },
    { field: 'company', headerName: 'Company', flex: 1 },
    {
      field: 'actions',
      headerName: '',
      width: 130,
      renderCell: (params) => (
        <Box display="flex"
          alignItems="center"
          justifyContent="flex-end"
          height="100%"
          gap={2}>
          <IconButton
            size="small"
            sx={{
              backgroundColor: '#DFCCBC',
              color: '#26201A',
              '&:hover': { backgroundColor: '#C2B2A4' },
              borderRadius: 2,
              p: 1,
            }}
            onClick={() => handleEditClick(params)}
          >
            <EditRoundedIcon fontSize="small" />
          </IconButton>
          <IconButton
            size="small"
            sx={{
              backgroundColor: '#FBE9E7',
              color: '#C62828',
              '&:hover': { backgroundColor: '#EF9A9A' },
              borderRadius: 2,
              p: 1,
            }}
            onClick={() => handleDeleteClick(params.row)}
          >
            <DeleteRoundedIcon fontSize="small" />
          </IconButton>
        </Box>
      )
    }
  ];

  return (
    <SectionContainer sx={{ width: '100%' }}>
      <Typography variant="h4" gutterBottom color="#26201AFF">
        Clients
      </Typography>

      <Dialog open={open} onClose={() => { setOpen(false); setEditingClient(null); }} maxWidth="md" fullWidth>
        <DialogTitle>{editingClient ? 'Edit Client' : 'Add Client'}</DialogTitle>
        <DialogContent>
          <AddOrEditClientsForm onAdd={handleAddOrEditClient} initialData={editingClient} onCancel={() => { setOpen(false); setEditingClient(null); }} />
        </DialogContent>
      </Dialog>

      <Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)}>
        <DialogTitle>Confirm Delete</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete{' '}
            <strong>{rowToDelete?.fullName}</strong>?
          </Typography>
          <Box mt={2} display="flex" justifyContent="flex-end" gap={1}>
            <Button onClick={() => setConfirmOpen(false)} className='button-transparent'>Cancel</Button>
            <Button variant="contained" onClick={confirmDelete} className="button-gold">Delete</Button>
          </Box>
        </DialogContent>
      </Dialog>

      <Box mt={2}>
        <DataGrid
          getRowHeight={() => 60}
          rows={rows}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5]}
          getRowSpacing={() => ({ top: 4, bottom: 4 })}
        />
        <Box display="flex" justifyContent="flex-end" mt={2}>
          <Button variant="contained" className="button-gold" onClick={() => setOpen(true)}>
            Add Client
          </Button>
        </Box>
      </Box>
    </SectionContainer>
  );
}