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,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Search as SearchIcon,
} from '@mui/icons-material';
import { articoliApi, tipiMaterialeApi, codiciCategoriaApi } from '../services/api';
import type { Articolo } from '../types';

const ArticoliPage: 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 [editingArticolo, setEditingArticolo] = useState<Articolo | null>(null);
  const [formData, setFormData] = useState<Partial<Articolo>>({});

  // Queries
  const { data: articoli, isLoading } = useQuery({
    queryKey: ['articoli'],
    queryFn: articoliApi.getAll,
  });

  const { data: tipiMateriale } = useQuery({
    queryKey: ['tipiMateriale'],
    queryFn: tipiMaterialeApi.getAll,
  });

  const { data: categorie } = useQuery({
    queryKey: ['categorie'],
    queryFn: codiciCategoriaApi.getAll,
  });

  // Mutations
  const saveMutation = useMutation({
    mutationFn: (data: Partial<Articolo>) =>
      editingArticolo ? articoliApi.update(editingArticolo.id, data) : articoliApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['articoli'] });
      handleCloseDialog();
    },
  });

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

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

    const searchLower = searchText.toLowerCase();
    return articoli.filter(
      (a) =>
        a.codice?.toLowerCase().includes(searchLower) ||
        a.descrizione?.toLowerCase().includes(searchLower)
    );
  }, [articoli, searchText]);

  const paginatedArticoli = filteredArticoli.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  const handleOpenDialog = (articolo?: Articolo) => {
    if (articolo) {
      setEditingArticolo(articolo);
      setFormData(articolo);
    } else {
      setEditingArticolo(null);
      setFormData({ attivo: true });
    }
    setDialogOpen(true);
  };

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

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

  const handleDelete = (articolo: Articolo) => {
    setEditingArticolo(articolo);
    setDeleteDialogOpen(true);
  };

  const handleConfirmDelete = () => {
    if (editingArticolo) {
      deleteMutation.mutate(editingArticolo.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">Articoli</Typography>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => handleOpenDialog()}>
          Nuovo Articolo
        </Button>
      </Box>

      <Paper>
        <Box p={2} borderBottom="1px solid #e0e0e0">
          <TextField
            size="small"
            placeholder="Cerca articolo..."
            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>Codice</TableCell>
                <TableCell>Descrizione</TableCell>
                <TableCell>Tipo Materiale</TableCell>
                <TableCell>Categoria</TableCell>
                <TableCell align="right">Qta Disp.</TableCell>
                <TableCell align="right">Qta Std A</TableCell>
                <TableCell align="right">Qta Std S</TableCell>
                <TableCell align="right">Qta Std B</TableCell>
                <TableCell>U.M.</TableCell>
                <TableCell align="center">Attivo</TableCell>
                <TableCell align="center">Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedArticoli.map((articolo) => (
                <TableRow key={articolo.id} hover>
                  <TableCell>
                    <Typography fontWeight="bold">{articolo.codice}</Typography>
                  </TableCell>
                  <TableCell>{articolo.descrizione}</TableCell>
                  <TableCell>{articolo.tipoMateriale?.descrizione || '-'}</TableCell>
                  <TableCell>{articolo.categoria?.descrizione || '-'}</TableCell>
                  <TableCell align="right">{articolo.qtaDisponibile || '-'}</TableCell>
                  <TableCell align="right">{articolo.qtaStdA || '-'}</TableCell>
                  <TableCell align="right">{articolo.qtaStdS || '-'}</TableCell>
                  <TableCell align="right">{articolo.qtaStdB || '-'}</TableCell>
                  <TableCell>{articolo.unitaMisura || '-'}</TableCell>
                  <TableCell align="center">
                    <Chip
                      label={articolo.attivo ? 'Si' : 'No'}
                      size="small"
                      color={articolo.attivo ? 'success' : 'default'}
                    />
                  </TableCell>
                  <TableCell align="center">
                    <IconButton size="small" onClick={() => handleOpenDialog(articolo)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton size="small" color="error" onClick={() => handleDelete(articolo)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {paginatedArticoli.length === 0 && (
                <TableRow>
                  <TableCell colSpan={11} align="center" sx={{ py: 4 }}>
                    <Typography color="textSecondary">Nessun articolo trovato</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[10, 25, 50, 100]}
          component="div"
          count={filteredArticoli.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>{editingArticolo ? 'Modifica Articolo' : 'Nuovo Articolo'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                fullWidth
                label="Codice"
                value={formData.codice || ''}
                onChange={(e) => setFormData({ ...formData, codice: e.target.value })}
                required
              />
            </Grid>
            <Grid size={{ xs: 12, md: 8 }}>
              <TextField
                fullWidth
                label="Descrizione"
                value={formData.descrizione || ''}
                onChange={(e) => setFormData({ ...formData, descrizione: e.target.value })}
                required
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <FormControl fullWidth>
                <InputLabel>Tipo Materiale</InputLabel>
                <Select
                  value={formData.tipoMaterialeId || ''}
                  label="Tipo Materiale"
                  onChange={(e) => setFormData({ ...formData, tipoMaterialeId: e.target.value as number })}
                >
                  <MenuItem value="">-- Seleziona --</MenuItem>
                  {tipiMateriale?.map((tipo) => (
                    <MenuItem key={tipo.id} value={tipo.id}>
                      {tipo.descrizione}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <FormControl fullWidth>
                <InputLabel>Categoria</InputLabel>
                <Select
                  value={formData.categoriaId || ''}
                  label="Categoria"
                  onChange={(e) => setFormData({ ...formData, categoriaId: e.target.value as number })}
                >
                  <MenuItem value="">-- Seleziona --</MenuItem>
                  {categorie?.map((cat) => (
                    <MenuItem key={cat.id} value={cat.id}>
                      {cat.descrizione}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, md: 3 }}>
              <TextField
                fullWidth
                label="Qta Disponibile"
                type="number"
                value={formData.qtaDisponibile || ''}
                onChange={(e) => setFormData({ ...formData, qtaDisponibile: Number(e.target.value) })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 3 }}>
              <TextField
                fullWidth
                label="Qta Std Adulti"
                type="number"
                value={formData.qtaStdA || ''}
                onChange={(e) => setFormData({ ...formData, qtaStdA: Number(e.target.value) })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 3 }}>
              <TextField
                fullWidth
                label="Qta Std Seduti"
                type="number"
                value={formData.qtaStdS || ''}
                onChange={(e) => setFormData({ ...formData, qtaStdS: Number(e.target.value) })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 3 }}>
              <TextField
                fullWidth
                label="Qta Std Buffet"
                type="number"
                value={formData.qtaStdB || ''}
                onChange={(e) => setFormData({ ...formData, qtaStdB: Number(e.target.value) })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 4 }}>
              <TextField
                fullWidth
                label="Unita di Misura"
                value={formData.unitaMisura || ''}
                onChange={(e) => setFormData({ ...formData, unitaMisura: 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 l'articolo "{editingArticolo?.codice} - {editingArticolo?.descrizione}"?
          </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 ArticoliPage;
