import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Typography,
  Button,
  Paper,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} 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 { risorseService, lookupService } from '../services/lookupService';
import { Risorsa } from '../types';

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

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

  const { data: tipiRisorsa = [] } = useQuery({
    queryKey: ['lookup', 'tipi-risorsa'],
    queryFn: () => lookupService.getTipiRisorsa(),
  });

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

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

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

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

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

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

  const columns: GridColDef[] = [
    { field: 'nome', headerName: 'Nome', width: 150 },
    { field: 'cognome', headerName: 'Cognome', width: 150 },
    {
      field: 'tipoRisorsa',
      headerName: 'Tipo',
      width: 150,
      valueGetter: (value: any) => value?.descrizione || '',
    },
    { field: 'telefono', headerName: 'Telefono', width: 130 },
    { field: 'email', headerName: 'Email', flex: 1, minWidth: 200 },
    {
      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 questa risorsa?')) {
                deleteMutation.mutate(params.row.id);
              }
            }}
          >
            <DeleteIcon />
          </IconButton>
        </Box>
      ),
    },
  ];

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

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

      <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
        <DialogTitle>{editingId ? 'Modifica Risorsa' : 'Nuova Risorsa'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Nome"
                fullWidth
                required
                value={formData.nome || ''}
                onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Cognome"
                fullWidth
                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 })}
                >
                  {tipiRisorsa.map((t) => (
                    <MenuItem key={t.id} value={t.id}>{t.descrizione}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </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 }}>
              <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>
  );
}
