import React, { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  TableSortLabel,
  IconButton,
  Button,
  TextField,
  InputAdornment,
  Chip,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Toolbar,
} from "@mui/material";
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Visibility as ViewIcon,
  Search as SearchIcon,
  ContentCopy as CopyIcon,
} from "@mui/icons-material";
import dayjs from "dayjs";
import { eventiApi } from "../services/api";
import type { Evento } from "../types";
import {
  StatoEvento,
  getStatoLabel,
  getStatoColor,
  getStatoTextColor,
} from "../types";

type Order = "asc" | "desc";

const EventiPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  // State
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [orderBy, setOrderBy] = useState<keyof Evento>("dataEvento");
  const [order, setOrder] = useState<Order>("desc");
  const [searchText, setSearchText] = useState("");
  const [statoFilter, setStatoFilter] = useState<StatoEvento | "">("");
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [eventoToDelete, setEventoToDelete] = useState<Evento | null>(null);

  // Queries
  const { data: eventi, isLoading } = useQuery({
    queryKey: ["eventi"],
    queryFn: eventiApi.getAll,
  });

  // Mutations
  const deleteMutation = useMutation({
    mutationFn: (id: number) => eventiApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["eventi"] });
      setDeleteDialogOpen(false);
      setEventoToDelete(null);
    },
  });

  const duplicateMutation = useMutation({
    mutationFn: (id: number) => eventiApi.duplicate(id),
    onSuccess: (newEvento) => {
      queryClient.invalidateQueries({ queryKey: ["eventi"] });
      navigate(`/eventi/${newEvento.id}`);
    },
  });

  // Filtering and sorting
  const filteredEventi = React.useMemo(() => {
    if (!eventi) return [];

    let result = [...eventi];

    // Filter by search text
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      result = result.filter(
        (e) =>
          e.descrizione?.toLowerCase().includes(searchLower) ||
          e.cliente?.ragioneSociale?.toLowerCase().includes(searchLower) ||
          e.location?.nome?.toLowerCase().includes(searchLower) ||
          e.codice?.toLowerCase().includes(searchLower),
      );
    }

    // Filter by stato
    if (statoFilter !== "") {
      result = result.filter((e) => e.stato === statoFilter);
    }

    // Sort
    result.sort((a, b) => {
      let aValue = a[orderBy];
      let bValue = b[orderBy];

      if (orderBy === "dataEvento") {
        aValue = dayjs(aValue as string).unix();
        bValue = dayjs(bValue as string).unix();
      }

      if (aValue === null || aValue === undefined) return 1;
      if (bValue === null || bValue === undefined) return -1;

      if (aValue < bValue) return order === "asc" ? -1 : 1;
      if (aValue > bValue) return order === "asc" ? 1 : -1;
      return 0;
    });

    return result;
  }, [eventi, searchText, statoFilter, orderBy, order]);

  // Pagination
  const paginatedEventi = filteredEventi.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage,
  );

  const handleRequestSort = (property: keyof Evento) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleChangePage = (_: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleDeleteClick = (evento: Evento) => {
    setEventoToDelete(evento);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = () => {
    if (eventoToDelete) {
      deleteMutation.mutate(eventoToDelete.id);
    }
  };

  const handleDuplicate = (id: number) => {
    duplicateMutation.mutate(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">Lista Eventi</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => navigate("/eventi/nuovo")}
        >
          Nuovo Evento
        </Button>
      </Box>

      <Paper>
        {/* Toolbar with filters */}
        <Toolbar
          sx={{
            pl: 2,
            pr: 2,
            backgroundColor: "#fafafa",
            borderBottom: "1px solid #e0e0e0",
          }}
        >
          <TextField
            size="small"
            placeholder="Cerca..."
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ mr: 2, width: 300 }}
          />

          <FormControl size="small" sx={{ minWidth: 150 }}>
            <InputLabel>Stato</InputLabel>
            <Select
              value={statoFilter}
              label="Stato"
              onChange={(e) =>
                setStatoFilter(e.target.value as StatoEvento | "")
              }
            >
              <MenuItem value="">Tutti</MenuItem>
              <MenuItem value={StatoEvento.Scheda}>Scheda</MenuItem>
              <MenuItem value={StatoEvento.Preventivo}>Preventivo</MenuItem>
              <MenuItem value={StatoEvento.Confermato}>Confermato</MenuItem>
            </Select>
          </FormControl>

          <Box flexGrow={1} />

          <Typography variant="body2" color="textSecondary">
            {filteredEventi.length} eventi trovati
          </Typography>
        </Toolbar>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: "#e3f2fd" }}>
                <TableCell>
                  <TableSortLabel
                    active={orderBy === "dataEvento"}
                    direction={orderBy === "dataEvento" ? order : "asc"}
                    onClick={() => handleRequestSort("dataEvento")}
                  >
                    Data
                  </TableSortLabel>
                </TableCell>
                <TableCell>Ora</TableCell>
                <TableCell>
                  <TableSortLabel
                    active={orderBy === "descrizione"}
                    direction={orderBy === "descrizione" ? order : "asc"}
                    onClick={() => handleRequestSort("descrizione")}
                  >
                    Descrizione
                  </TableSortLabel>
                </TableCell>
                <TableCell>Cliente</TableCell>
                <TableCell>Location</TableCell>
                <TableCell align="center">Ospiti</TableCell>
                <TableCell align="right">Costo</TableCell>
                <TableCell>Stato</TableCell>
                <TableCell align="center" sx={{ width: 150 }}>
                  Azioni
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedEventi.map((evento) => (
                <TableRow
                  key={evento.id}
                  hover
                  sx={{
                    backgroundColor: getStatoColor(evento.stato),
                    cursor: "pointer",
                    "&:hover": {
                      backgroundColor: getStatoColor(evento.stato),
                      filter: "brightness(0.95)",
                    },
                  }}
                  onClick={() => navigate(`/eventi/${evento.id}`)}
                >
                  <TableCell>
                    <Typography variant="body2" fontWeight="bold">
                      {dayjs(evento.dataEvento).format("DD/MM/YYYY")}
                    </Typography>
                    <Typography variant="caption" color="textSecondary">
                      {dayjs(evento.dataEvento).format("dddd")}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    {evento.oraInizio || "-"}
                    {evento.oraFine && ` - ${evento.oraFine}`}
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {evento.descrizione || "-"}
                    </Typography>
                    {evento.codice && (
                      <Typography variant="caption" color="textSecondary">
                        {evento.codice}
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>{evento.cliente?.ragioneSociale || "-"}</TableCell>
                  <TableCell>{evento.location?.nome || "-"}</TableCell>
                  <TableCell align="center">
                    {evento.numeroOspiti || "-"}
                  </TableCell>
                  <TableCell align="right">
                    {evento.costoTotale
                      ? `${evento.costoTotale.toLocaleString("it-IT", {
                          style: "currency",
                          currency: "EUR",
                        })}`
                      : "-"}
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={getStatoLabel(evento.stato)}
                      size="small"
                      sx={{
                        backgroundColor: getStatoTextColor(evento.stato),
                        color: "white",
                        fontWeight: "bold",
                      }}
                    />
                  </TableCell>
                  <TableCell
                    align="center"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <IconButton
                      size="small"
                      onClick={() => navigate(`/eventi/${evento.id}`)}
                      title="Visualizza"
                    >
                      <ViewIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => navigate(`/eventi/${evento.id}/modifica`)}
                      title="Modifica"
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDuplicate(evento.id)}
                      title="Duplica"
                    >
                      <CopyIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteClick(evento)}
                      title="Elimina"
                      color="error"
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {paginatedEventi.length === 0 && (
                <TableRow>
                  <TableCell colSpan={9} align="center" sx={{ py: 4 }}>
                    <Typography color="textSecondary">
                      Nessun evento trovato
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[10, 25, 50, 100]}
          component="div"
          count={filteredEventi.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
          labelRowsPerPage="Righe per pagina:"
          labelDisplayedRows={({ from, to, count }) =>
            `${from}-${to} di ${count}`
          }
        />
      </Paper>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>Conferma Eliminazione</DialogTitle>
        <DialogContent>
          <Typography>
            Sei sicuro di voler eliminare l'evento "
            {eventoToDelete?.descrizione}" del{" "}
            {eventoToDelete &&
              dayjs(eventoToDelete.dataEvento).format("DD/MM/YYYY")}
            ?
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>Annulla</Button>
          <Button
            onClick={handleDeleteConfirm}
            color="error"
            variant="contained"
            disabled={deleteMutation.isPending}
          >
            Elimina
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EventiPage;
