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 { locationApi } from '../services/api';
import type { Location } from '../types';

const LocationPage: 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 [editingLocation, setEditingLocation] = useState<Location | null>(null);
  const [formData, setFormData] = useState<Partial<Location>>({});

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

  // Mutations
  const saveMutation = useMutation({
    mutationFn: (data: Partial<Location>) =>
      editingLocation ? locationApi.update(editingLocation.id, data) : locationApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['location'] });
      handleCloseDialog();
    },
  });

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

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

    const searchLower = searchText.toLowerCase();
    return locations.filter(
      (l) =>
        l.nome?.toLowerCase().includes(searchLower) ||
        l.citta?.toLowerCase().includes(searchLower) ||
        l.referente?.toLowerCase().includes(searchLower)
    );
  }, [locations, searchText]);

  const paginatedLocations = filteredLocations.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  const handleOpenDialog = (location?: Location) => {
    if (location) {
      setEditingLocation(location);
      setFormData(location);
    } else {
      setEditingLocation(null);
      setFormData({ attivo: true });
    }
    setDialogOpen(true);
  };

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

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

  const handleDelete = (location: Location) => {
    setEditingLocation(location);
    setDeleteDialogOpen(true);
  };

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

      <Paper>
        <Box p={2} borderBottom="1px solid #e0e0e0">
          <TextField
            size="small"
            placeholder="Cerca location..."
            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>Indirizzo</TableCell>
                <TableCell>Citta</TableCell>
                <TableCell>Referente</TableCell>
                <TableCell>Telefono</TableCell>
                <TableCell align="right">Distanza (km)</TableCell>
                <TableCell align="center">Attivo</TableCell>
                <TableCell align="center">Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedLocations.map((location) => (
                <TableRow key={location.id} hover>
                  <TableCell>
                    <Typography fontWeight="bold">{location.nome}</Typography>
                  </TableCell>
                  <TableCell>{location.indirizzo || '-'}</TableCell>
                  <TableCell>
                    {location.citta || '-'}
                    {location.provincia && ` (${location.provincia})`}
                  </TableCell>
                  <TableCell>{location.referente || '-'}</TableCell>
                  <TableCell>{location.telefono || '-'}</TableCell>
                  <TableCell align="right">{location.distanzaKm || '-'}</TableCell>
                  <TableCell align="center">
                    <Chip
                      label={location.attivo ? 'Si' : 'No'}
                      size="small"
                      color={location.attivo ? 'success' : 'default'}
                    />
                  </TableCell>
                  <TableCell align="center">
                    <IconButton size="small" onClick={() => handleOpenDialog(location)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton size="small" color="error" onClick={() => handleDelete(location)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {paginatedLocations.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} align="center" sx={{ py: 4 }}>
                    <Typography color="textSecondary">Nessuna location trovata</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[10, 25, 50]}
          component="div"
          count={filteredLocations.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>{editingLocation ? 'Modifica Location' : 'Nuova Location'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Nome"
                value={formData.nome || ''}
                onChange={(e) => setFormData({ ...formData, nome: 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="Referente"
                value={formData.referente || ''}
                onChange={(e) => setFormData({ ...formData, referente: e.target.value })}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                fullWidth
                label="Distanza (km)"
                type="number"
                value={formData.distanzaKm || ''}
                onChange={(e) => setFormData({ ...formData, distanzaKm: Number(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 location "{editingLocation?.nome}"?
          </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 LocationPage;
