import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  Tooltip,
  LinearProgress,
  Switch,
  FormControlLabel,
  TextField,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  InputAdornment,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import {
  Refresh as RefreshIcon,
  Edit as EditIcon,
  RestartAlt as ResetIcon,
  ExpandMore as ExpandMoreIcon,
  Code as CodeIcon,
  Preview as PreviewIcon,
  Help as HelpIcon,
  ContentCopy as CopyIcon,
} from "@mui/icons-material";
import * as Icons from "@mui/icons-material";
import { autoCodeService } from "../services/autoCodeService";
import type {
  AutoCodeDto,
  AutoCodeUpdateDto,
  PlaceholderInfo,
} from "../types/autoCode";
import { groupByModule, moduleNames, moduleIcons } from "../types/autoCode";

export default function AutoCodesAdminPage() {
  const queryClient = useQueryClient();
  const [editingConfig, setEditingConfig] = useState<AutoCodeDto | null>(null);
  const [confirmReset, setConfirmReset] = useState<string | null>(null);
  const [previewCode, setPreviewCode] = useState<string | null>(null);
  const [showHelp, setShowHelp] = useState(false);
  const [expandedModule, setExpandedModule] = useState<string | false>("core");

  // Query per tutte le configurazioni
  const {
    data: configs = [],
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["autocodes"],
    queryFn: () => autoCodeService.getAll(),
  });

  // Query per i placeholder disponibili
  const { data: placeholders = [] } = useQuery({
    queryKey: ["autocodes", "placeholders"],
    queryFn: () => autoCodeService.getPlaceholders(),
  });

  // Mutation per aggiornare configurazione
  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: AutoCodeUpdateDto }) =>
      autoCodeService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["autocodes"] });
      setEditingConfig(null);
    },
  });

  // Mutation per reset sequenza
  const resetMutation = useMutation({
    mutationFn: (entityCode: string) =>
      autoCodeService.resetSequence(entityCode),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["autocodes"] });
      setConfirmReset(null);
    },
  });

  // Mutation per preview codice
  const previewMutation = useMutation({
    mutationFn: (entityCode: string) => autoCodeService.previewCode(entityCode),
    onSuccess: (data) => {
      setPreviewCode(data.code);
    },
  });

  // Raggruppa configurazioni per modulo
  const groupedConfigs = groupByModule(configs);

  // Helper per ottenere icona modulo
  const getModuleIcon = (moduleCode: string) => {
    const iconName = moduleIcons[moduleCode] || "Extension";
    const IconComponent = (Icons as Record<string, React.ComponentType>)[
      iconName
    ];
    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,
          flexWrap: "wrap",
          gap: 2,
        }}
      >
        <Box>
          <Typography variant="h4" gutterBottom>
            Codici Automatici
          </Typography>
          <Typography color="text.secondary">
            Configura i pattern per la generazione automatica dei codici
          </Typography>
        </Box>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="outlined"
            startIcon={<HelpIcon />}
            onClick={() => setShowHelp(true)}
          >
            Guida Pattern
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => refetch()}
          >
            Aggiorna
          </Button>
        </Box>
      </Box>

      {/* Accordion per moduli */}
      {Object.entries(groupedConfigs).map(([moduleCode, moduleConfigs]) => (
        <Accordion
          key={moduleCode}
          expanded={expandedModule === moduleCode}
          onChange={(_, isExpanded) =>
            setExpandedModule(isExpanded ? moduleCode : false)
          }
          sx={{ mb: 1 }}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
              {getModuleIcon(moduleCode)}
              <Typography variant="h6">
                {moduleNames[moduleCode] || moduleCode}
              </Typography>
              <Chip
                label={`${moduleConfigs.length} configurazioni`}
                size="small"
                variant="outlined"
              />
            </Box>
          </AccordionSummary>
          <AccordionDetails>
            <TableContainer component={Paper} variant="outlined">
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Entita</TableCell>
                    <TableCell>Prefisso</TableCell>
                    <TableCell>Pattern</TableCell>
                    <TableCell>Esempio</TableCell>
                    <TableCell>Sequenza</TableCell>
                    <TableCell>Reset</TableCell>
                    <TableCell align="center">Stato</TableCell>
                    <TableCell align="right">Azioni</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {moduleConfigs.map((config) => (
                    <TableRow key={config.id} hover>
                      <TableCell>
                        <Box>
                          <Typography variant="body2" fontWeight="medium">
                            {config.entityName}
                          </Typography>
                          <Typography variant="caption" color="text.secondary">
                            {config.entityCode}
                          </Typography>
                        </Box>
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={config.prefix || "-"}
                          size="small"
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell>
                        <Typography
                          variant="body2"
                          sx={{ fontFamily: "monospace", fontSize: "0.85rem" }}
                        >
                          {config.pattern}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Box
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            gap: 0.5,
                          }}
                        >
                          <Typography
                            variant="body2"
                            sx={{
                              fontFamily: "monospace",
                              color: "primary.main",
                              fontWeight: "medium",
                            }}
                          >
                            {config.exampleCode}
                          </Typography>
                          <Tooltip title="Anteprima prossimo codice">
                            <IconButton
                              size="small"
                              onClick={() =>
                                previewMutation.mutate(config.entityCode)
                              }
                              disabled={!config.isEnabled}
                            >
                              <PreviewIcon fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2">
                          {config.lastSequence}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        {config.resetSequenceMonthly ? (
                          <Chip label="Mensile" size="small" color="info" />
                        ) : config.resetSequenceYearly ? (
                          <Chip label="Annuale" size="small" color="warning" />
                        ) : (
                          <Chip label="Mai" size="small" variant="outlined" />
                        )}
                      </TableCell>
                      <TableCell align="center">
                        <Chip
                          label={config.isEnabled ? "Attivo" : "Disattivo"}
                          size="small"
                          color={config.isEnabled ? "success" : "default"}
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Modifica">
                          <IconButton
                            size="small"
                            onClick={() => setEditingConfig(config)}
                          >
                            <EditIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Reset sequenza">
                          <IconButton
                            size="small"
                            onClick={() => setConfirmReset(config.entityCode)}
                            disabled={!config.isEnabled}
                          >
                            <ResetIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </AccordionDetails>
        </Accordion>
      ))}

      {/* Dialog modifica configurazione */}
      <EditConfigDialog
        config={editingConfig}
        placeholders={placeholders}
        onClose={() => setEditingConfig(null)}
        onSave={(data) => {
          if (editingConfig) {
            updateMutation.mutate({ id: editingConfig.id, data });
          }
        }}
        isSaving={updateMutation.isPending}
        error={updateMutation.error as Error | null}
      />

      {/* Dialog conferma reset */}
      <Dialog
        open={!!confirmReset}
        onClose={() => setConfirmReset(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Conferma Reset Sequenza</DialogTitle>
        <DialogContent>
          <Typography>
            Sei sicuro di voler resettare la sequenza per{" "}
            <strong>
              {configs.find((c) => c.entityCode === confirmReset)?.entityName}
            </strong>
            ?
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            La sequenza verra riportata a 0. Il prossimo codice generato partira
            da 1.
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmReset(null)}>Annulla</Button>
          <Button
            color="warning"
            variant="contained"
            onClick={() => confirmReset && resetMutation.mutate(confirmReset)}
            disabled={resetMutation.isPending}
            startIcon={
              resetMutation.isPending ? (
                <CircularProgress size={16} color="inherit" />
              ) : (
                <ResetIcon />
              )
            }
          >
            Reset
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog anteprima codice */}
      <Dialog
        open={!!previewCode}
        onClose={() => setPreviewCode(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Anteprima Prossimo Codice</DialogTitle>
        <DialogContent>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              p: 3,
              bgcolor: "grey.100",
              borderRadius: 1,
              gap: 1,
            }}
          >
            <CodeIcon color="primary" />
            <Typography
              variant="h5"
              sx={{ fontFamily: "monospace", fontWeight: "bold" }}
            >
              {previewCode}
            </Typography>
            <Tooltip title="Copia">
              <IconButton
                size="small"
                onClick={() => {
                  navigator.clipboard.writeText(previewCode || "");
                }}
              >
                <CopyIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          </Box>
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ display: "block", mt: 2, textAlign: "center" }}
          >
            Questo e il codice che verra generato alla prossima creazione.
            <br />
            La sequenza non e stata incrementata.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPreviewCode(null)}>Chiudi</Button>
        </DialogActions>
      </Dialog>

      {/* Dialog guida pattern */}
      <Dialog
        open={showHelp}
        onClose={() => setShowHelp(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>Guida ai Pattern</DialogTitle>
        <DialogContent dividers>
          <Typography variant="body2" paragraph>
            I pattern definiscono come vengono generati i codici automatici.
            Puoi combinare testo statico e placeholder dinamici.
          </Typography>

          <Typography variant="subtitle2" gutterBottom sx={{ mt: 2 }}>
            Placeholder Disponibili
          </Typography>
          <TableContainer component={Paper} variant="outlined" sx={{ mb: 3 }}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Placeholder</TableCell>
                  <TableCell>Descrizione</TableCell>
                  <TableCell>Esempio</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {placeholders.map((p) => (
                  <TableRow key={p.placeholder}>
                    <TableCell>
                      <Typography sx={{ fontFamily: "monospace" }}>
                        {p.placeholder}
                      </Typography>
                    </TableCell>
                    <TableCell>{p.description}</TableCell>
                    <TableCell>
                      <Typography sx={{ fontFamily: "monospace" }}>
                        {p.example}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>

          <Typography variant="subtitle2" gutterBottom>
            Esempi di Pattern
          </Typography>
          <Grid container spacing={2}>
            <Grid size={{ xs: 12, md: 6 }}>
              <Card variant="outlined">
                <CardContent>
                  <Typography
                    variant="body2"
                    sx={{ fontFamily: "monospace", mb: 1 }}
                  >
                    {"{PREFIX}-{SEQ:5}"}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Risultato: ART-00001, ART-00002, ...
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <Card variant="outlined">
                <CardContent>
                  <Typography
                    variant="body2"
                    sx={{ fontFamily: "monospace", mb: 1 }}
                  >
                    {"{PREFIX}{YYYY}-{SEQ:5}"}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Risultato: EVT2025-00001 (reset annuale)
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <Card variant="outlined">
                <CardContent>
                  <Typography
                    variant="body2"
                    sx={{ fontFamily: "monospace", mb: 1 }}
                  >
                    {"{PREFIX}{YY}{MM}-{SEQ:4}"}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Risultato: MOV2511-0001 (reset mensile)
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <Card variant="outlined">
                <CardContent>
                  <Typography
                    variant="body2"
                    sx={{ fontFamily: "monospace", mb: 1 }}
                  >
                    {"FT{YYYY}/{SEQ:5}"}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Risultato: FT2025/00001 (formato fattura)
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowHelp(false)}>Chiudi</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// Dialog per modifica configurazione
interface EditConfigDialogProps {
  config: AutoCodeDto | null;
  placeholders: PlaceholderInfo[];
  onClose: () => void;
  onSave: (data: AutoCodeUpdateDto) => void;
  isSaving: boolean;
  error: Error | null;
}

function EditConfigDialog({
  config,
  placeholders,
  onClose,
  onSave,
  isSaving,
  error,
}: EditConfigDialogProps) {
  const [formData, setFormData] = useState<AutoCodeUpdateDto>({});

  // Reset form quando cambia config
  const handleOpen = () => {
    if (config) {
      setFormData({
        prefix: config.prefix,
        pattern: config.pattern,
        resetSequenceYearly: config.resetSequenceYearly,
        resetSequenceMonthly: config.resetSequenceMonthly,
        isEnabled: config.isEnabled,
        isReadOnly: config.isReadOnly,
        description: config.description,
      });
    }
  };

  const handleSave = () => {
    onSave(formData);
  };

  // Calcola esempio in tempo reale
  const getExampleFromPattern = (pattern: string, prefix: string | null) => {
    const now = new Date();
    return pattern
      .replace("{PREFIX}", prefix || "")
      .replace("{YEAR}", now.getFullYear().toString())
      .replace("{YYYY}", now.getFullYear().toString())
      .replace("{YY}", now.getFullYear().toString().slice(-2))
      .replace("{MONTH}", (now.getMonth() + 1).toString().padStart(2, "0"))
      .replace("{MM}", (now.getMonth() + 1).toString().padStart(2, "0"))
      .replace("{DAY}", now.getDate().toString().padStart(2, "0"))
      .replace("{DD}", now.getDate().toString().padStart(2, "0"))
      .replace(/\{SEQ:(\d+)\}/g, (_, digits) => "X".repeat(parseInt(digits)));
  };

  const currentExample = getExampleFromPattern(
    formData.pattern || config?.pattern || "",
    formData.prefix !== undefined ? formData.prefix : config?.prefix || null,
  );

  return (
    <Dialog
      open={!!config}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      TransitionProps={{ onEntered: handleOpen }}
    >
      {config && (
        <>
          <DialogTitle>
            Modifica Configurazione: {config.entityName}
          </DialogTitle>
          <DialogContent dividers>
            <Grid container spacing={2}>
              <Grid size={{ xs: 12 }}>
                <TextField
                  label="Prefisso"
                  value={formData.prefix ?? config.prefix ?? ""}
                  onChange={(e) =>
                    setFormData({ ...formData, prefix: e.target.value || null })
                  }
                  fullWidth
                  size="small"
                  helperText="Testo sostituito nel placeholder {PREFIX}"
                />
              </Grid>

              <Grid size={{ xs: 12 }}>
                <TextField
                  label="Pattern"
                  value={formData.pattern ?? config.pattern}
                  onChange={(e) =>
                    setFormData({ ...formData, pattern: e.target.value })
                  }
                  fullWidth
                  size="small"
                  helperText="Pattern per generazione codice"
                  InputProps={{
                    sx: { fontFamily: "monospace" },
                    endAdornment: (
                      <InputAdornment position="end">
                        <Tooltip
                          title={
                            <Box>
                              {placeholders.map((p) => (
                                <Typography
                                  key={p.placeholder}
                                  variant="caption"
                                  display="block"
                                >
                                  {p.placeholder}: {p.description}
                                </Typography>
                              ))}
                            </Box>
                          }
                        >
                          <HelpIcon fontSize="small" color="action" />
                        </Tooltip>
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>

              <Grid size={{ xs: 12 }}>
                <Box
                  sx={{
                    p: 2,
                    bgcolor: "grey.100",
                    borderRadius: 1,
                    textAlign: "center",
                  }}
                >
                  <Typography variant="caption" color="text.secondary">
                    Anteprima:
                  </Typography>
                  <Typography
                    variant="h6"
                    sx={{ fontFamily: "monospace", color: "primary.main" }}
                  >
                    {currentExample}
                  </Typography>
                </Box>
              </Grid>

              <Grid size={{ xs: 12 }}>
                <FormControl fullWidth size="small">
                  <InputLabel>Reset Sequenza</InputLabel>
                  <Select
                    value={
                      (formData.resetSequenceMonthly ??
                      config.resetSequenceMonthly)
                        ? "monthly"
                        : (formData.resetSequenceYearly ??
                            config.resetSequenceYearly)
                          ? "yearly"
                          : "never"
                    }
                    label="Reset Sequenza"
                    onChange={(e) => {
                      const value = e.target.value;
                      setFormData({
                        ...formData,
                        resetSequenceYearly: value === "yearly",
                        resetSequenceMonthly: value === "monthly",
                      });
                    }}
                  >
                    <MenuItem value="never">Mai</MenuItem>
                    <MenuItem value="yearly">Ogni anno</MenuItem>
                    <MenuItem value="monthly">Ogni mese</MenuItem>
                  </Select>
                </FormControl>
              </Grid>

              <Grid size={{ xs: 12 }}>
                <TextField
                  label="Descrizione"
                  value={formData.description ?? config.description ?? ""}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      description: e.target.value || null,
                    })
                  }
                  fullWidth
                  size="small"
                  multiline
                  rows={2}
                />
              </Grid>

              <Grid size={{ xs: 6 }}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={formData.isEnabled ?? config.isEnabled}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          isEnabled: e.target.checked,
                        })
                      }
                    />
                  }
                  label="Generazione attiva"
                />
              </Grid>

              <Grid size={{ xs: 6 }}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={formData.isReadOnly ?? config.isReadOnly}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          isReadOnly: e.target.checked,
                        })
                      }
                    />
                  }
                  label="Codice non modificabile"
                />
              </Grid>
            </Grid>

            {error && (
              <Alert severity="error" sx={{ mt: 2 }}>
                {error.message || "Errore durante il salvataggio"}
              </Alert>
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={onClose}>Annulla</Button>
            <Button
              variant="contained"
              onClick={handleSave}
              disabled={isSaving}
              startIcon={
                isSaving ? <CircularProgress size={16} color="inherit" /> : null
              }
            >
              Salva
            </Button>
          </DialogActions>
        </>
      )}
    </Dialog>
  );
}
