import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Chip,
  Grid,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  Tooltip,
  LinearProgress,
  Divider,
  Switch,
  FormControlLabel,
} from "@mui/material";
import {
  Refresh as RefreshIcon,
  Info as InfoIcon,
  Warning as WarningIcon,
  Schedule as ScheduleIcon,
  Autorenew as RenewIcon,
} from "@mui/icons-material";
import * as Icons from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { useModules } from "../contexts/ModuleContext";
import { moduleService } from "../services/moduleService";
import type { ModuleDto } from "../types/module";
import {
  formatPrice,
  formatDate,
  getDaysRemainingText,
  getSubscriptionStatusColor,
  getSubscriptionStatusText,
} from "../types/module";

export default function ModulesAdminPage() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { modules, isLoading, refreshModules } = useModules();
  const [selectedModule, setSelectedModule] = useState<ModuleDto | null>(null);
  const [confirmDisable, setConfirmDisable] = useState<string | null>(null);

  // Query per moduli in scadenza
  const { data: expiringModules = [] } = useQuery({
    queryKey: ["modules", "expiring"],
    queryFn: () => moduleService.getExpiring(30),
  });

  // Mutation per disattivare modulo
  const disableMutation = useMutation({
    mutationFn: (code: string) => moduleService.disable(code),
    onSuccess: () => {
      refreshModules();
      setConfirmDisable(null);
    },
  });

  // Mutation per rinnovare subscription
  const renewMutation = useMutation({
    mutationFn: (code: string) => moduleService.renewSubscription(code),
    onSuccess: () => {
      refreshModules();
    },
  });

  // Mutation per controllare scadenze
  const checkExpiredMutation = useMutation({
    mutationFn: () => moduleService.checkExpired(),
    onSuccess: () => {
      refreshModules();
    },
  });

  // Helper per ottenere icona modulo
  const getModuleIcon = (iconName?: string) => {
    if (!iconName) return <Icons.Extension />;
    const IconComponent = (Icons as Record<string, React.ComponentType>)[
      iconName.replace(/\s+/g, "")
    ];
    return IconComponent ? <IconComponent /> : <Icons.Extension />;
  };

  if (isLoading) {
    return (
      <Box sx={{ p: 3 }}>
        <LinearProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      {/* Header */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
        }}
      >
        <Box>
          <Typography variant="h4" gutterBottom>
            {t("modules.admin.title")}
          </Typography>
          <Typography color="text.secondary">
            {t("modules.admin.subtitle")}
          </Typography>
        </Box>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="outlined"
            startIcon={<ScheduleIcon />}
            onClick={() => checkExpiredMutation.mutate()}
            disabled={checkExpiredMutation.isPending}
          >
            {t("modules.admin.checkExpired")}
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => refreshModules()}
          >
            {t("modules.admin.refresh")}
          </Button>
        </Box>
      </Box>

      {/* Alert moduli in scadenza */}
      {expiringModules.length > 0 && (
        <Alert severity="warning" sx={{ mb: 3 }} icon={<WarningIcon />}>
          <Typography variant="subtitle2" gutterBottom>
            {t("modules.admin.expiringWarning", {
              count: expiringModules.length,
            })}
          </Typography>
          <Box sx={{ display: "flex", gap: 1, mt: 1, flexWrap: "wrap" }}>
            {expiringModules.map((m) => (
              <Chip
                key={m.code}
                label={`${m.name} (${getDaysRemainingText(m.subscription?.daysRemaining)})`}
                size="small"
                color="warning"
              />
            ))}
          </Box>
        </Alert>
      )}

      {/* Griglia moduli */}
      <Grid container spacing={3}>
        {modules.map((module) => (
          <Grid size={{ xs: 12, sm: 6, md: 4 }} key={module.code}>
            <ModuleCard
              module={module}
              onToggle={() => {
                if (module.isEnabled && !module.isCore) {
                  setConfirmDisable(module.code);
                } else if (!module.isEnabled) {
                  navigate(`/modules/purchase/${module.code}`);
                }
              }}
              onInfo={() => setSelectedModule(module)}
              onRenew={() => renewMutation.mutate(module.code)}
              isRenewing={renewMutation.isPending}
              getIcon={getModuleIcon}
              t={t}
            />
          </Grid>
        ))}
      </Grid>

      {/* Dialog dettagli modulo */}
      <Dialog
        open={!!selectedModule}
        onClose={() => setSelectedModule(null)}
        maxWidth="sm"
        fullWidth
      >
        {selectedModule && (
          <>
            <DialogTitle>
              <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                {getModuleIcon(selectedModule.icon)}
                {selectedModule.name}
              </Box>
            </DialogTitle>
            <DialogContent dividers>
              <Typography paragraph>{selectedModule.description}</Typography>

              <Divider sx={{ my: 2 }} />

              <Grid container spacing={2}>
                <Grid size={{ xs: 6 }}>
                  <Typography variant="caption" color="text.secondary">
                    {t("modules.admin.annualPrice")}
                  </Typography>
                  <Typography variant="h6">
                    {formatPrice(selectedModule.basePrice)}
                  </Typography>
                </Grid>
                <Grid size={{ xs: 6 }}>
                  <Typography variant="caption" color="text.secondary">
                    {t("modules.admin.monthlyPrice")}
                  </Typography>
                  <Typography variant="h6">
                    {formatPrice(selectedModule.monthlyPrice)}
                  </Typography>
                </Grid>
              </Grid>

              {selectedModule.dependencies.length > 0 && (
                <Box sx={{ mt: 2 }}>
                  <Typography variant="caption" color="text.secondary">
                    {t("modules.admin.dependencies")}
                  </Typography>
                  <Box sx={{ display: "flex", gap: 0.5, mt: 0.5 }}>
                    {selectedModule.dependencies.map((dep) => (
                      <Chip key={dep} label={dep} size="small" />
                    ))}
                  </Box>
                </Box>
              )}

              {selectedModule.subscription && (
                <>
                  <Divider sx={{ my: 2 }} />
                  <Typography variant="subtitle2" gutterBottom>
                    {t("modules.admin.subscriptionDetails")}
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.type")}
                      </Typography>
                      <Typography>
                        {selectedModule.subscription.subscriptionTypeName}
                      </Typography>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.status")}
                      </Typography>
                      <Typography>
                        <Chip
                          label={getSubscriptionStatusText(
                            selectedModule.subscription,
                          )}
                          size="small"
                          color={getSubscriptionStatusColor(
                            selectedModule.subscription,
                          )}
                        />
                      </Typography>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.startDate")}
                      </Typography>
                      <Typography>
                        {formatDate(selectedModule.subscription.startDate)}
                      </Typography>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.endDate")}
                      </Typography>
                      <Typography>
                        {formatDate(selectedModule.subscription.endDate)}
                      </Typography>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.daysRemaining")}
                      </Typography>
                      <Typography>
                        {getDaysRemainingText(
                          selectedModule.subscription.daysRemaining,
                        )}
                      </Typography>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Typography variant="caption" color="text.secondary">
                        {t("modules.admin.autoRenew")}
                      </Typography>
                      <Typography>
                        {selectedModule.subscription.autoRenew
                          ? t("modules.admin.yes")
                          : t("modules.admin.no")}
                      </Typography>
                    </Grid>
                  </Grid>
                </>
              )}
            </DialogContent>
            <DialogActions>
              <Button onClick={() => setSelectedModule(null)}>
                {t("common.close")}
              </Button>
            </DialogActions>
          </>
        )}
      </Dialog>

      {/* Dialog conferma disattivazione */}
      <Dialog
        open={!!confirmDisable}
        onClose={() => setConfirmDisable(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>{t("modules.admin.disableConfirmTitle")}</DialogTitle>
        <DialogContent>
          <Typography>
            {t("modules.admin.disableConfirmText")}{" "}
            <strong>
              {modules.find((m) => m.code === confirmDisable)?.name}
            </strong>
            ?
          </Typography>
          <Typography color="text.secondary" sx={{ mt: 1 }}>
            {t("modules.admin.disableConfirmSubtext")}
          </Typography>
          {disableMutation.isError && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {(disableMutation.error as Error)?.message ||
                t("common.error")}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmDisable(null)}>
            {t("common.cancel")}
          </Button>
          <Button
            color="error"
            variant="contained"
            onClick={() =>
              confirmDisable && disableMutation.mutate(confirmDisable)
            }
            disabled={disableMutation.isPending}
            startIcon={
              disableMutation.isPending ? (
                <CircularProgress size={16} color="inherit" />
              ) : null
            }
          >
            {t("modules.admin.disable")}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// Componente Card singolo modulo
interface ModuleCardProps {
  module: ModuleDto;
  onToggle: () => void;
  onInfo: () => void;
  onRenew: () => void;
  isRenewing: boolean;
  getIcon: (iconName?: string) => React.ReactNode;
  t: (key: string) => string;
}

function ModuleCard({
  module,
  onToggle,
  onInfo,
  onRenew,
  isRenewing,
  getIcon,
  t,
}: ModuleCardProps) {
  const statusColor = getSubscriptionStatusColor(module.subscription);
  const statusText = getSubscriptionStatusText(module.subscription);

  return (
    <Card
      sx={{
        height: "100%",
        display: "flex",
        flexDirection: "column",
        borderLeft: 4,
        borderColor: module.isEnabled
          ? statusColor === "success"
            ? "success.main"
            : statusColor === "warning"
              ? "warning.main"
              : "error.main"
          : "grey.300",
        opacity: module.isEnabled ? 1 : 0.7,
      }}
    >
      <CardContent sx={{ flexGrow: 1 }}>
        {/* Header */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            mb: 2,
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <Box sx={{ color: module.isEnabled ? "primary.main" : "grey.500" }}>
              {getIcon(module.icon)}
            </Box>
            <Typography variant="h6">{module.name}</Typography>
          </Box>
          <Box>
            {module.isCore ? (
              <Chip label={t("modules.admin.core")} size="small" color="info" />
            ) : (
              <Chip label={statusText} size="small" color={statusColor} />
            )}
          </Box>
        </Box>

        {/* Descrizione */}
        <Typography
          variant="body2"
          color="text.secondary"
          sx={{
            mb: 2,
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
            overflow: "hidden",
          }}
        >
          {module.description}
        </Typography>

        {/* Info subscription */}
        {module.subscription && module.isEnabled && (
          <Box sx={{ mb: 2 }}>
            <Typography variant="caption" color="text.secondary">
              {t("modules.admin.endDate")}: {formatDate(module.subscription.endDate)}
              {module.subscription.daysRemaining !== undefined &&
                module.subscription.daysRemaining <= 30 && (
                  <Chip
                    label={getDaysRemainingText(
                      module.subscription.daysRemaining,
                    )}
                    size="small"
                    color={
                      module.subscription.daysRemaining <= 7
                        ? "error"
                        : "warning"
                    }
                    sx={{ ml: 1 }}
                  />
                )}
            </Typography>
          </Box>
        )}

        {/* Prezzo */}
        <Typography variant="body2">
          {formatPrice(module.basePrice)}
          <Typography component="span" variant="caption" color="text.secondary">
            /anno
          </Typography>
        </Typography>
      </CardContent>

      {/* Actions */}
      <Box
        sx={{
          px: 2,
          pb: 2,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Box>
          <Tooltip title={t("modules.admin.details")}>
            <IconButton size="small" onClick={onInfo}>
              <InfoIcon />
            </IconButton>
          </Tooltip>
          {module.isEnabled &&
            !module.isCore &&
            module.subscription?.isExpiringSoon && (
              <Tooltip title={t("modules.admin.renew")}>
                <IconButton
                  size="small"
                  color="warning"
                  onClick={onRenew}
                  disabled={isRenewing}
                >
                  {isRenewing ? <CircularProgress size={20} /> : <RenewIcon />}
                </IconButton>
              </Tooltip>
            )}
        </Box>

        {!module.isCore && (
          <FormControlLabel
            control={
              <Switch
                checked={module.isEnabled}
                onChange={onToggle}
                color={module.isEnabled ? "success" : "default"}
              />
            }
            label={module.isEnabled ? t("modules.admin.active") : t("modules.admin.inactive")}
            labelPlacement="start"
          />
        )}
      </Box>
    </Card>
  );
}
