import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  IconButton,
  Button,
  TextField,
  InputAdornment,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  CircularProgress,
  Chip,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Search as SearchIcon,
} from '@mui/icons-material';
import { clientiApi } from '../services/api';
import type { Cliente } from '../types';

const ClientiPage: React.FC = () => {
  const queryClient = useQueryClient();

  // State
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [searchText, setSearchText] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [editingCliente, setEditingCliente] = useState<Cliente | null>(null);
  const [formData, setFormData] = useState<Partial<Cliente>>({});

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

  // Mutations
  const saveMutation = useMutation({
    mutationFn: (data: Partial<Cliente>) =>
      editingCliente ? clientiApi.update(editingCliente.id, data) : clientiApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['clienti'] });
      handleCloseDialog();
    },
  });

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

  // Filter
  const filteredClienti = React.useMemo(() => {
    if (!clienti) return [];
    if (!searchText) return clienti;

    const searchLower = searchText.toLowerCase();
    return clienti.filter(
      (c) =>
        c.ragioneSociale?.toLowerCase().includes(searchLower) ||
        c.citta?.toLowerCase().includes(searchLower) ||
        c.email?.toLowerCase().includes(searchLower) ||
        c.telefono?.includes(searchText)
    );
  }, [clienti, searchText]);

  const paginatedClienti = filteredClienti.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  const handleOpenDialog = (cliente?: Cliente) => {
    if (cliente) {
      setEditingCliente(cliente);
      setFormData(cliente);
    } else {
      setEditingCliente(null);
      setFormData({ attivo: true });
    }
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditingCliente(null);
    setFormData({});
  };

  const handleSave = () => {
    saveMutation.mutate(formData);
  };

  const handleDelete = (cliente: Cliente) => {
    setEditingCliente(cliente);
    setDeleteDialogOpen(true);
  };

  const handleConfirmDelete = () => {
    if (editingCliente) {
      deleteMutation.mutate(editingCliente.id);
    }
  };

  if (isLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4">Clienti</Typography>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => handleOpenDialog()}>
          Nuovo Cliente
        </Button>
      </Box>

      <Paper>
        <Box p={2} borderBottom="1px solid #e0e0e0">
          <TextField
            size="small"
            placeholder="Cerca cliente..."
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ width: 300 }}
          />
        </Box>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: '#e3f2fd' }}>
                <TableCell>Ragione Sociale</TableCell>
                <TableCell>Indirizzo</TableCell>
                <TableCell>Citta</TableCell>
                <TableCell>Telefono</TableCell>
                <TableCell>Email</TableCell>
                <TableCell>P.IVA</TableCell>
                <TableCell align="center">Attivo</TableCell>
                <TableCell align="center">Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedClienti.map((cliente) => (
                <TableRow key={cliente.id} hover>
                  <TableCell>
                    <Typography fontWeight="bold">{cliente.ragioneSociale}</Typography>
                  </TableCell>
                  <TableCell>{cliente.indirizzo || '-'}</TableCell>
                  <TableCell>
                    {cliente.citta || '-'}
                    {cliente.provincia && ` (${cliente.provincia})`}
                  </TableCell>
                  <TableCell>{cliente.telefono || '-'}</TableCell>
                  <TableCell>{cliente.email || '-'}</TableCell>
                  <TableCell>{cliente.partitaIva || '-'}</TableCell>
                  <TableCell align="center">
                    <Chip
                      label={cliente.attivo ? 'Si' : 'No'}
                      size="small"
                      color={cliente.attivo ? 'success' : 'default'}
                    />
                  </TableCell>
                  <TableCell align="center">
                    <IconButton size="small" onClick={() => handleOpenDialog(cliente)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton size="small" color="error" onClick={() => handleDelete(cliente)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {paginatedClienti.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} align="center" sx={{ py: 4 }}>
                    <Typography color="textSecondary">Nessun cliente trovato</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[10, 25, 50]}
          component="div"
          count={filteredClienti.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={(_, p) => setPage(p)}
          onRowsPerPageChange={(e) => {
            setRowsPerPage(parseInt(e.target.value, 10));
            setPage(0);
          }}
          labelRowsPerPage="Righe per pagina:"
        />
      </Paper>

      {/* Edit/Create Dialog */}
      <Dialog open={dialogOpen} onClose={handleCloseDialog} maxWidth="md" fullWidth>
        <DialogTitle>{editingCliente ? 'Modifica Cliente' : 'Nuovo Cliente'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Ragione Sociale"
                value={formData.ragioneSociale || ''}
                onChange={(e) => setFormData({ ...formData, ragioneSociale: e.target.value })}
                required
              />
            </Grid>
            <Grid size={{ xs: 12, md: 8 }}>
              <TextField
                fullWidth
                label="Indirizzo"
                value={formData.indirizzo || ''}
                onChange={(e) => setFormData({ ...formData, indirizzo: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                fullWidth
                label="CAP"
                value={formData.cap || ''}
                onChange={(e) => setFormData({ ...formData, cap: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 8 }}>
              <TextField
                fullWidth
                label="Citta"
                value={formData.citta || ''}
                onChange={(e) => setFormData({ ...formData, citta: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                fullWidth
                label="Provincia"
                value={formData.provincia || ''}
                onChange={(e) => setFormData({ ...formData, provincia: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Telefono"
                value={formData.telefono || ''}
                onChange={(e) => setFormData({ ...formData, telefono: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Email"
                type="email"
                value={formData.email || ''}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="PEC"
                value={formData.pec || ''}
                onChange={(e) => setFormData({ ...formData, pec: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Codice Fiscale"
                value={formData.codiceFiscale || ''}
                onChange={(e) => setFormData({ ...formData, codiceFiscale: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Partita IVA"
                value={formData.partitaIva || ''}
                onChange={(e) => setFormData({ ...formData, partitaIva: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Codice Destinatario"
                value={formData.codiceDestinatario || ''}
                onChange={(e) => setFormData({ ...formData, codiceDestinatario: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Note"
                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={handleSave} disabled={saveMutation.isPending}>
            Salva
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
        <DialogTitle>Conferma Eliminazione</DialogTitle>
        <DialogContent>
          <Typography>
            Sei sicuro di voler eliminare il cliente "{editingCliente?.ragioneSociale}"?
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Annulla</Button>
          <Button
            color="error"
            variant="contained"
            onClick={handleConfirmDelete}
            disabled={deleteMutation.isPending}
          >
            Elimina
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ClientiPage;
