
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Typography,
  Button,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  LinearProgress,
  Switch,
  FormControlLabel,
  TextField,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tooltip,
} from "@mui/material";
import Grid from "@mui/material/Grid";
import {
  Refresh as RefreshIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ExpandMore as ExpandMoreIcon,
  Add as AddIcon,
} from "@mui/icons-material";
import * as Icons from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { customFieldService } from "../services/customFieldService";
import {
  CustomFieldDefinition,
  CustomFieldType,
  groupByEntity,
  entityNames,
  entityIcons,
  fieldTypeNames,
} from "../types/customFields";

export default function CustomFieldsAdminPage() {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const [editingConfig, setEditingConfig] = useState<CustomFieldDefinition | null>(
    null,
  );
  const [isCreating, setIsCreating] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState<number | null>(null);
  const [expandedEntity, setExpandedEntity] = useState<string | false>("Client");

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

  // Mutation per creare configurazione
  const createMutation = useMutation({
    mutationFn: (data: Omit<CustomFieldDefinition, "id">) =>
      customFieldService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["customFields"] });
      setIsCreating(false);
    },
  });

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

  // Mutation per eliminare configurazione
  const deleteMutation = useMutation({
    mutationFn: (id: number) => customFieldService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["customFields"] });
      setConfirmDelete(null);
    },
  });

  // Raggruppa configurazioni per entità
  const groupedConfigs = groupByEntity(configs);

  // Helper per ottenere icona entità
  const getEntityIcon = (entityCode: string) => {
    const iconName = entityIcons[entityCode] || "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>
            {t("customFields.title")}
          </Typography>
          <Typography color="text.secondary">
            {t("customFields.title")}
          </Typography>
        </Box>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => setIsCreating(true)}
          >
            {t("customFields.newField")}
          </Button>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => refetch()}
          >
            {t("common.refresh")}
          </Button>
        </Box>
      </Box>

      {/* Accordion per entità */}
      {Object.entries(entityNames).map(([entityCode, entityName]) => {
        const entityConfigs = groupedConfigs[entityCode] || [];
        return (
          <Accordion
            key={entityCode}
            expanded={expandedEntity === entityCode}
            onChange={(_, isExpanded) =>
              setExpandedEntity(isExpanded ? entityCode : false)
            }
            sx={{ mb: 1 }}
          >
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                {getEntityIcon(entityCode)}
                <Typography variant="h6">
                  {t(`customFields.entities.${entityCode.toLowerCase()}`) || entityName}
                </Typography>
                <Chip
                  label={`${entityConfigs.length} campi`}
                  size="small"
                  variant="outlined"
                />
              </Box>
            </AccordionSummary>
            <AccordionDetails>
              {entityConfigs.length === 0 ? (
                <Typography
                  color="text.secondary"
                  align="center"
                  sx={{ py: 2 }}
                >
                  {t("customFields.noFields")}
                </Typography>
              ) : (
                <TableContainer component={Paper} variant="outlined">
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>{t("customFields.label")}</TableCell>
                        <TableCell>{t("customFields.fieldName")}</TableCell>
                        <TableCell>{t("customFields.type")}</TableCell>
                        <TableCell align="center">
                          {t("customFields.required")}
                        </TableCell>
                        <TableCell align="center">
                          {t("customFields.order")}
                        </TableCell>
                        <TableCell align="center">
                          {t("autoCodes.status")}
                        </TableCell>
                        <TableCell align="right">
                          {t("common.actions")}
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {entityConfigs.map((config) => (
                        <TableRow key={config.id} hover>
                          <TableCell>
                            <Typography variant="body2" fontWeight="medium">
                              {config.label}
                            </Typography>
                            {config.description && (
                              <Typography
                                variant="caption"
                                color="text.secondary"
                                display="block"
                              >
                                {config.description}
                              </Typography>
                            )}
                          </TableCell>
                          <TableCell>
                            <Typography
                              variant="body2"
                              sx={{ fontFamily: "monospace" }}
                            >
                              {config.fieldName}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Chip
                              label={t(`customFields.types.${CustomFieldType[config.type].toLowerCase()}`)}
                              size="small"
                              variant="outlined"
                            />
                          </TableCell>
                          <TableCell align="center">
                            {config.isRequired ? (
                              <Chip
                                label={t("autoCodes.yes")}
                                size="small"
                                color="warning"
                              />
                            ) : (
                              <Chip
                                label={t("autoCodes.no")}
                                size="small"
                                variant="outlined"
                              />
                            )}
                          </TableCell>
                          <TableCell align="center">
                            {config.sortOrder}
                          </TableCell>
                          <TableCell align="center">
                            <Chip
                              label={
                                config.isActive
                                  ? t("modules.admin.active")
                                  : t("modules.admin.inactive")
                              }
                              size="small"
                              color={config.isActive ? "success" : "default"}
                            />
                          </TableCell>
                          <TableCell align="right">
                            <Tooltip title={t("common.edit")}>
                              <IconButton
                                size="small"
                                onClick={() => setEditingConfig(config)}
                              >
                                <EditIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title={t("common.delete")}>
                              <IconButton
                                size="small"
                                color="error"
                                onClick={() => setConfirmDelete(config.id)}
                              >
                                <DeleteIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              )}
            </AccordionDetails>
          </Accordion>
        );
      })}

      {/* Dialog creazione/modifica */}
      <EditConfigDialog
        config={editingConfig}
        isCreating={isCreating}
        onClose={() => {
          setEditingConfig(null);
          setIsCreating(false);
        }}
        onSave={(data) => {
          if (isCreating) {
            createMutation.mutate(data as Omit<CustomFieldDefinition, "id">);
          } else if (editingConfig) {
            updateMutation.mutate({
              id: editingConfig.id,
              data: data as CustomFieldDefinition,
            });
          }
        }}
        isSaving={createMutation.isPending || updateMutation.isPending}
        error={
          (createMutation.error || updateMutation.error) as Error | null
        }
        t={t}
      />

      {/* Dialog conferma eliminazione */}
      <Dialog
        open={!!confirmDelete}
        onClose={() => setConfirmDelete(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>{t("common.confirmDelete")}</DialogTitle>
        <DialogContent>
          <Typography>{t("customFields.deleteConfirm")}</Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            {t("common.irreversibleAction")}
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmDelete(null)}>
            {t("common.cancel")}
          </Button>
          <Button
            color="error"
            variant="contained"
            onClick={() =>
              confirmDelete && deleteMutation.mutate(confirmDelete)
            }
            disabled={deleteMutation.isPending}
            startIcon={
              deleteMutation.isPending ? (
                <CircularProgress size={16} color="inherit" />
              ) : (
                <DeleteIcon />
              )
            }
          >
            {t("common.delete")}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// Dialog per creazione/modifica configurazione
interface EditConfigDialogProps {
  config: CustomFieldDefinition | null;
  isCreating: boolean;
  onClose: () => void;
  onSave: (
    data: Omit<CustomFieldDefinition, "id"> | CustomFieldDefinition,
  ) => void;
  isSaving: boolean;
  error: Error | null;
  t: (key: string) => string;
}

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

  // Reset form quando apre
  const handleOpen = () => {
    if (config) {
      setFormData({
        entityName: config.entityName,
        fieldName: config.fieldName,
        label: config.label,
        type: config.type,
        isRequired: config.isRequired,
        optionsJson: config.optionsJson,
        defaultValue: config.defaultValue,
        description: config.description,
        sortOrder: config.sortOrder,
        isActive: config.isActive,
      });
    } else {
      setFormData({
        entityName: "Client",
        type: CustomFieldType.Text,
        isRequired: false,
        isActive: true,
        sortOrder: 0,
      });
    }
  };

  const handleSave = () => {
    onSave(formData as Omit<CustomFieldDefinition, "id">);
  };

  return (
    <Dialog
      open={!!config || isCreating}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      TransitionProps={{ onEntered: handleOpen }}
    >
      <DialogTitle>
        {isCreating
          ? t("customFields.newField")
          : `${t("customFields.editField")}: ${config?.label}`}
      </DialogTitle>
      <DialogContent dividers>
        <Grid container spacing={2}>
          {isCreating && (
            <Grid size={{ xs: 12 }}>
              <FormControl fullWidth size="small">
                <InputLabel>{t("customFields.entity")}</InputLabel>
                <Select
                  value={formData.entityName || "Client"}
                  label={t("customFields.entity")}
                  onChange={(e) =>
                    setFormData({ ...formData, entityName: e.target.value })
                  }
                >
                  {Object.entries(entityNames).map(([code, name]) => (
                    <MenuItem key={code} value={code}>
                      {t(`customFields.entities.${code.toLowerCase()}`) || name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
          )}

          <Grid size={{ xs: 12, md: 6 }}>
            <TextField
              label={t("customFields.label")}
              value={formData.label || ""}
              onChange={(e) =>
                setFormData({ ...formData, label: e.target.value })
              }
              fullWidth
              size="small"
              required
            />
          </Grid>

          <Grid size={{ xs: 12, md: 6 }}>
            <TextField
              label={t("customFields.fieldName")}
              value={formData.fieldName || ""}
              onChange={(e) =>
                setFormData({ ...formData, fieldName: e.target.value })
              }
              fullWidth
              size="small"
              required
              disabled={!isCreating}
              helperText={isCreating ? t("customFields.fieldNameHelper") : ""}
            />
          </Grid>

          <Grid size={{ xs: 12 }}>
            <FormControl fullWidth size="small">
              <InputLabel>{t("customFields.type")}</InputLabel>
              <Select
                value={formData.type ?? CustomFieldType.Text}
                label={t("customFields.type")}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    type: Number(e.target.value) as CustomFieldType,
                  })
                }
                disabled={!isCreating}
              >
                {Object.entries(fieldTypeNames).map(([type]) => {
                  const typeEnum = Number(type) as CustomFieldType;
                  return (
                    <MenuItem key={type} value={type}>
                      {t(`customFields.types.${CustomFieldType[typeEnum].toLowerCase()}`)}
                    </MenuItem>
                  );
                })}
              </Select>
            </FormControl>
          </Grid>

          {(formData.type === CustomFieldType.Select ||
            formData.type === CustomFieldType.MultiSelect) && (
              <Grid size={{ xs: 12 }}>
                <TextField
                  label={t("customFields.optionsJson")}
                  value={formData.optionsJson || ""}
                  onChange={(e) =>
                    setFormData({ ...formData, optionsJson: e.target.value })
                  }
                  fullWidth
                  size="small"
                  multiline
                  rows={3}
                  helperText={t("customFields.optionsHelper")}
                  InputProps={{ sx: { fontFamily: "monospace" } }}
                />
              </Grid>
            )}

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

          <Grid size={{ xs: 6 }}>
            <TextField
              label={t("customFields.order")}
              type="number"
              value={formData.sortOrder || 0}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  sortOrder: parseInt(e.target.value),
                })
              }
              fullWidth
              size="small"
            />
          </Grid>

          <Grid size={{ xs: 6 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={formData.isRequired || false}
                  onChange={(e) =>
                    setFormData({ ...formData, isRequired: e.target.checked })
                  }
                />
              }
              label={t("customFields.required")}
            />
          </Grid>

          <Grid size={{ xs: 6 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={formData.isActive !== false}
                  onChange={(e) =>
                    setFormData({ ...formData, isActive: e.target.checked })
                  }
                />
              }
              label={t("modules.admin.active")}
            />
          </Grid>
        </Grid>

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


