
import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,

  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  FormControlLabel,
  Checkbox,
  Snackbar,
  Alert
} from '@mui/material';
import { DataGrid, GridColDef, GridActionsCellItem } from '@mui/x-data-grid';
import { Add as AddIcon, Edit as EditIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { CustomFieldDefinition, CustomFieldType } from '../types/customFields';
import { customFieldService } from '../services/customFieldService';

const ENTITIES = [
  { value: 'Cliente', label: 'Clienti' },
  { value: 'Articolo', label: 'Articoli (Catering)' },
  { value: 'Evento', label: 'Eventi' },
  { value: 'WarehouseArticle', label: 'Articoli Magazzino' },
  { value: 'WarehouseLocation', label: 'Magazzini' },
  { value: 'Risorsa', label: 'Risorse (Staff)' }
];

const FIELD_TYPES = [
  { value: CustomFieldType.Text, label: 'Testo' },
  { value: CustomFieldType.Number, label: 'Numero' },
  { value: CustomFieldType.Date, label: 'Data' },
  { value: CustomFieldType.Boolean, label: 'Booleano (Sì/No)' },
  { value: CustomFieldType.Select, label: 'Lista a discesa' },
  { value: CustomFieldType.TextArea, label: 'Area di testo' },
  { value: CustomFieldType.Color, label: 'Colore' },
  { value: CustomFieldType.Url, label: 'URL' },
  { value: CustomFieldType.Email, label: 'Email' }
];

const CustomFieldsAdminPage: React.FC = () => {
  const [selectedEntity, setSelectedEntity] = useState<string>(ENTITIES[0].value);
  const [fields, setFields] = useState<CustomFieldDefinition[]>([]);
  const [loading, setLoading] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [currentField, setCurrentField] = useState<Partial<CustomFieldDefinition>>({});
  const [snackbar, setSnackbar] = useState<{ open: boolean, message: string, severity: 'success' | 'error' }>({
    open: false,
    message: '',
    severity: 'success'
  });

  const showSnackbar = (message: string, severity: 'success' | 'error') => {
    setSnackbar({ open: true, message, severity });
  };

  const handleCloseSnackbar = () => setSnackbar({ ...snackbar, open: false });

  const loadFields = async () => {
    setLoading(true);
    try {
      const data = await customFieldService.getByEntity(selectedEntity);
      setFields(data);
    } catch (error) {
      showSnackbar('Errore nel caricamento dei campi', 'error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadFields();
  }, [selectedEntity]);

  const handleSave = async () => {
    try {
      if (currentField.id) {
        await customFieldService.update(currentField.id, currentField as CustomFieldDefinition);
        showSnackbar('Campo aggiornato con successo', 'success');
      } else {
        await customFieldService.create({
          ...currentField,
          entityName: selectedEntity,
          isActive: true,
          sortOrder: fields.length + 1
        } as CustomFieldDefinition);
        showSnackbar('Campo creato con successo', 'success');
      }
      setDialogOpen(false);
      loadFields();
    } catch (error) {
      showSnackbar('Errore nel salvataggio', 'error');
    }
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Sei sicuro di voler eliminare questo campo?')) {
      try {
        await customFieldService.delete(id);
        showSnackbar('Campo eliminato', 'success');
        loadFields();
      } catch (error) {
        showSnackbar('Errore durante l\'eliminazione', 'error');
      }
    }
  };

  const columns: GridColDef[] = [
    { field: 'label', headerName: 'Etichetta', flex: 1 },
    { field: 'fieldName', headerName: 'Nome Interno', flex: 1 },
    {
      field: 'type',
      headerName: 'Tipo',
      width: 150,
      valueFormatter: (params) => FIELD_TYPES.find(t => t.value === params.value)?.label
    },
    {
      field: 'isRequired',
      headerName: 'Obbligatorio',
      width: 120,
      type: 'boolean'
    },
    {
      field: 'sortOrder',
      headerName: 'Ordine',
      width: 100,
      type: 'number',
      editable: true
    },
    {
      field: 'actions',
      type: 'actions',
      headerName: 'Azioni',
      width: 100,
      getActions: (params) => [
        <GridActionsCellItem
          icon={<EditIcon />}
          label="Modifica"
          onClick={() => {
            setCurrentField(params.row);
            setDialogOpen(true);
          }}
        />,
        <GridActionsCellItem
          icon={<DeleteIcon />}
          label="Elimina"
          onClick={() => handleDelete(params.row.id)}
        />,
      ],
    },
  ];

  return (
    <Box p={3}>
      <Typography variant="h4" gutterBottom>
        Gestione Campi Personalizzati
      </Typography>

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box display="flex" flexWrap="wrap" gap={2} alignItems="center">
            <Box flexBasis={{ xs: '100%', md: '33%' }} flexGrow={1}>
              <FormControl fullWidth>
                <InputLabel>Entità</InputLabel>
                <Select
                  value={selectedEntity}
                  label="Entità"
                  onChange={(e) => setSelectedEntity(e.target.value)}
                >
                  {ENTITIES.map(e => (
                    <MenuItem key={e.value} value={e.value}>{e.label}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>
            <Box flexBasis={{ xs: '100%', md: 'auto' }} display="flex" justifyContent="flex-end">
              <Button
                variant="contained"
                startIcon={<AddIcon />}
                onClick={() => {
                  setCurrentField({
                    type: CustomFieldType.Text,
                    isRequired: false,
                    entityName: selectedEntity
                  });
                  setDialogOpen(true);
                }}
              >
                Nuovo Campo
              </Button>
            </Box>
          </Box>
        </CardContent>
      </Card>

      <div style={{ height: 600, width: '100%' }}>
        <DataGrid
          rows={fields}
          columns={columns}
          loading={loading}
          disableRowSelectionOnClick
        />
      </div>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{currentField.id ? 'Modifica Campo' : 'Nuovo Campo'}</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
            <TextField
              label="Etichetta (Label)"
              fullWidth
              value={currentField.label || ''}
              onChange={(e) => setCurrentField({ ...currentField, label: e.target.value })}
              required
            />
            <TextField
              label="Nome Interno (es. data_nascita)"
              fullWidth
              value={currentField.fieldName || ''}
              onChange={(e) => setCurrentField({ ...currentField, fieldName: e.target.value })}
              required
              helperText="Deve essere univoco per l'entità. Usa solo lettere minuscole e underscore."
              disabled={!!currentField.id}
            />
            <FormControl fullWidth>
              <InputLabel>Tipo</InputLabel>
              <Select
                value={currentField.type}
                label="Tipo"
                onChange={(e) => setCurrentField({ ...currentField, type: e.target.value as CustomFieldType })}
              >
                {FIELD_TYPES.map(t => (
                  <MenuItem key={t.value} value={t.value}>{t.label}</MenuItem>
                ))}
              </Select>
            </FormControl>

            {currentField.type === CustomFieldType.Select && (
              <TextField
                label="Opzioni (JSON Array)"
                fullWidth
                multiline
                rows={3}
                value={currentField.optionsJson || ''}
                onChange={(e) => setCurrentField({ ...currentField, optionsJson: e.target.value })}
                placeholder='["Opzione 1", "Opzione 2"]'
                helperText="Inserisci un array JSON valido di stringhe"
              />
            )}

            <TextField
              label="Descrizione / Helper Text"
              fullWidth
              value={currentField.description || ''}
              onChange={(e) => setCurrentField({ ...currentField, description: e.target.value })}
            />

            <FormControlLabel
              control={
                <Checkbox
                  checked={currentField.isRequired || false}
                  onChange={(e) => setCurrentField({ ...currentField, isRequired: e.target.checked })}
                />
              }
              label="Obbligatorio"
            />

            <TextField
              label="Ordine"
              type="number"
              fullWidth
              value={currentField.sortOrder || 0}
              onChange={(e) => setCurrentField({ ...currentField, sortOrder: parseInt(e.target.value) })}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Annulla</Button>
          <Button onClick={handleSave} variant="contained">Salva</Button>
        </DialogActions>
      </Dialog>

      <Snackbar open={snackbar.open} autoHideDuration={6000} onClose={handleCloseSnackbar}>
        <Alert onClose={handleCloseSnackbar} severity={snackbar.severity} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default CustomFieldsAdminPage;

