import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Typography,
  Button,
  Paper,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Grid,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { clientiService } from '../services/lookupService';
import { Cliente } from '../types';

export default function ClientiPage() {
  const queryClient = useQueryClient();
  const [openDialog, setOpenDialog] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<Partial<Cliente>>({ attivo: true });

  const { data: clienti = [], isLoading } = useQuery({
    queryKey: ['clienti'],
    queryFn: () => clientiService.getAll(),
  });

  const createMutation = useMutation({
    mutationFn: (data: Partial<Cliente>) => clientiService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clienti'] });
      handleCloseDialog();
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<Cliente> }) => clientiService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clienti'] });
      handleCloseDialog();
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => clientiService.delete(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['clienti'] }),
  });

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setEditingId(null);
    setFormData({ attivo: true });
  };

  const handleEdit = (cliente: Cliente) => {
    setFormData(cliente);
    setEditingId(cliente.id);
    setOpenDialog(true);
  };

  const handleSubmit = () => {
    if (editingId) {
      updateMutation.mutate({ id: editingId, data: formData });
    } else {
      createMutation.mutate(formData);
    }
  };

  const columns: GridColDef[] = [
    { field: 'ragioneSociale', headerName: 'Ragione Sociale', flex: 1, minWidth: 200 },
    { field: 'citta', headerName: 'Città', width: 150 },
    { field: 'provincia', headerName: 'Prov.', width: 80 },
    { field: 'telefono', headerName: 'Telefono', width: 130 },
    { field: 'email', headerName: 'Email', width: 200 },
    { field: 'partitaIva', headerName: 'P.IVA', width: 130 },
    {
      field: 'actions',
      headerName: 'Azioni',
      width: 120,
      sortable: false,
      renderCell: (params) => (
        <Box>
          <IconButton size="small" onClick={() => handleEdit(params.row)}>
            <EditIcon />
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => {
              if (confirm('Eliminare questo cliente?')) {
                deleteMutation.mutate(params.row.id);
              }
            }}
          >
            <DeleteIcon />
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h4">Clienti</Typography>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpenDialog(true)}>
          Nuovo Cliente
        </Button>
      </Box>

      <Paper sx={{ height: 600, width: '100%' }}>
        <DataGrid
          rows={clienti}
          columns={columns}
          loading={isLoading}
          pageSizeOptions={[10, 25, 50]}
          initialState={{
            pagination: { paginationModel: { pageSize: 25 } },
          }}
          disableRowSelectionOnClick
        />
      </Paper>

      <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="md" fullWidth>
        <DialogTitle>{editingId ? 'Modifica Cliente' : 'Nuovo Cliente'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                label="Ragione Sociale"
                fullWidth
                required
                value={formData.ragioneSociale || ''}
                onChange={(e) => setFormData({ ...formData, ragioneSociale: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 8 }}>
              <TextField
                label="Indirizzo"
                fullWidth
                value={formData.indirizzo || ''}
                onChange={(e) => setFormData({ ...formData, indirizzo: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                label="CAP"
                fullWidth
                value={formData.cap || ''}
                onChange={(e) => setFormData({ ...formData, cap: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 8 }}>
              <TextField
                label="Città"
                fullWidth
                value={formData.citta || ''}
                onChange={(e) => setFormData({ ...formData, citta: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                label="Provincia"
                fullWidth
                value={formData.provincia || ''}
                onChange={(e) => setFormData({ ...formData, provincia: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Telefono"
                fullWidth
                value={formData.telefono || ''}
                onChange={(e) => setFormData({ ...formData, telefono: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Email"
                fullWidth
                type="email"
                value={formData.email || ''}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="PEC"
                fullWidth
                value={formData.pec || ''}
                onChange={(e) => setFormData({ ...formData, pec: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Codice Fiscale"
                fullWidth
                value={formData.codiceFiscale || ''}
                onChange={(e) => setFormData({ ...formData, codiceFiscale: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Partita IVA"
                fullWidth
                value={formData.partitaIva || ''}
                onChange={(e) => setFormData({ ...formData, partitaIva: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Codice Destinatario"
                fullWidth
                value={formData.codiceDestinatario || ''}
                onChange={(e) => setFormData({ ...formData, codiceDestinatario: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <TextField
                label="Note"
                fullWidth
                multiline
                rows={3}
                value={formData.note || ''}
                onChange={(e) => setFormData({ ...formData, note: e.target.value })}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Annulla</Button>
          <Button variant="contained" onClick={handleSubmit}>
            {editingId ? 'Salva' : 'Crea'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
