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 { risorseApi, tipiRisorsaApi } from '../services/api';
import type { Risorsa } from '../types';

const RisorsePage: 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 [editingRisorsa, setEditingRisorsa] = useState<Risorsa | null>(null);
  const [formData, setFormData] = useState<Partial<Risorsa>>({});

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

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

  // Mutations
  const saveMutation = useMutation({
    mutationFn: (data: Partial<Risorsa>) =>
      editingRisorsa ? risorseApi.update(editingRisorsa.id, data) : risorseApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['risorse'] });
      handleCloseDialog();
    },
  });

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

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

    const searchLower = searchText.toLowerCase();
    return risorse.filter(
      (r) =>
        r.nome?.toLowerCase().includes(searchLower) ||
        r.cognome?.toLowerCase().includes(searchLower) ||
        r.email?.toLowerCase().includes(searchLower)
    );
  }, [risorse, searchText]);

  const paginatedRisorse = filteredRisorse.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  const handleOpenDialog = (risorsa?: Risorsa) => {
    if (risorsa) {
      setEditingRisorsa(risorsa);
      setFormData(risorsa);
    } else {
      setEditingRisorsa(null);
      setFormData({ attivo: true });
    }
    setDialogOpen(true);
  };

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

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

  const handleDelete = (risorsa: Risorsa) => {
    setEditingRisorsa(risorsa);
    setDeleteDialogOpen(true);
  };

  const handleConfirmDelete = () => {
    if (editingRisorsa) {
      deleteMutation.mutate(editingRisorsa.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">Risorse</Typography>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => handleOpenDialog()}>
          Nuova Risorsa
        </Button>
      </Box>

      <Paper>
        <Box p={2} borderBottom="1px solid #e0e0e0">
          <TextField
            size="small"
            placeholder="Cerca risorsa..."
            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>Nome</TableCell>
                <TableCell>Cognome</TableCell>
                <TableCell>Tipo</TableCell>
                <TableCell>Telefono</TableCell>
                <TableCell>Email</TableCell>
                <TableCell>Note</TableCell>
                <TableCell align="center">Attivo</TableCell>
                <TableCell align="center">Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedRisorse.map((risorsa) => (
                <TableRow key={risorsa.id} hover>
                  <TableCell>
                    <Typography fontWeight="bold">{risorsa.nome}</Typography>
                  </TableCell>
                  <TableCell>{risorsa.cognome || '-'}</TableCell>
                  <TableCell>
                    {risorsa.tipoRisorsa?.descrizione && (
                      <Chip label={risorsa.tipoRisorsa.descrizione} size="small" />
                    )}
                  </TableCell>
                  <TableCell>{risorsa.telefono || '-'}</TableCell>
                  <TableCell>{risorsa.email || '-'}</TableCell>
                  <TableCell>{risorsa.note || '-'}</TableCell>
                  <TableCell align="center">
                    <Chip
                      label={risorsa.attivo ? 'Si' : 'No'}
                      size="small"
                      color={risorsa.attivo ? 'success' : 'default'}
                    />
                  </TableCell>
                  <TableCell align="center">
                    <IconButton size="small" onClick={() => handleOpenDialog(risorsa)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton size="small" color="error" onClick={() => handleDelete(risorsa)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {paginatedRisorse.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} align="center" sx={{ py: 4 }}>
                    <Typography color="textSecondary">Nessuna risorsa trovata</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[10, 25, 50]}
          component="div"
          count={filteredRisorse.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="sm" fullWidth>
        <DialogTitle>{editingRisorsa ? 'Modifica Risorsa' : 'Nuova Risorsa'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Nome"
                value={formData.nome || ''}
                onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
                required
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Cognome"
                value={formData.cognome || ''}
                onChange={(e) => setFormData({ ...formData, cognome: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <FormControl fullWidth>
                <InputLabel>Tipo Risorsa</InputLabel>
                <Select
                  value={formData.tipoRisorsaId || ''}
                  label="Tipo Risorsa"
                  onChange={(e) => setFormData({ ...formData, tipoRisorsaId: e.target.value as number })}
                >
                  <MenuItem value="">-- Seleziona --</MenuItem>
                  {tipiRisorsa?.map((tipo) => (
                    <MenuItem key={tipo.id} value={tipo.id}>
                      {tipo.descrizione}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </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 }}>
              <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 la risorsa "{editingRisorsa?.nome} {editingRisorsa?.cognome}"?
          </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 RisorsePage;
