import { useState } from "react";
import {
  Box,
  Paper,
  Typography,
  Button,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormControlLabel,
  Switch,
  Grid,
  Alert,
  Card,
  CardContent,
  CardActions,
  Tooltip,
} from "@mui/material";
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Star as StarIcon,
  StarBorder as StarBorderIcon,
  Warehouse as WarehouseIcon,
} from "@mui/icons-material";
import { useTranslation, Trans } from "react-i18next";
import {
  useWarehouses,
  useCreateWarehouse,
  useUpdateWarehouse,
  useDeleteWarehouse,
  useSetDefaultWarehouse,
} from "../hooks";
import {
  WarehouseLocationDto,
  WarehouseType,
  warehouseTypeLabels,
} from "../types";

const initialFormData = {
  code: "",
  alternativeCode: "",
  name: "",
  description: "",
  type: WarehouseType.Physical,
  address: "",
  isDefault: false,
  isActive: true,
  sortOrder: 0,
};

export default function WarehouseLocationsPage() {
  const { t } = useTranslation();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [editingWarehouse, setEditingWarehouse] =
    useState<WarehouseLocationDto | null>(null);
  const [warehouseToDelete, setWarehouseToDelete] =
    useState<WarehouseLocationDto | null>(null);
  const [formData, setFormData] = useState(initialFormData);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const { data: warehouses, isLoading, error } = useWarehouses();
  const createMutation = useCreateWarehouse();
  const updateMutation = useUpdateWarehouse();
  const deleteMutation = useDeleteWarehouse();
  const setDefaultMutation = useSetDefaultWarehouse();

  const handleOpenDialog = (warehouse?: WarehouseLocationDto) => {
    if (warehouse) {
      setEditingWarehouse(warehouse);
      setFormData({
        code: warehouse.code,
        alternativeCode: warehouse.alternativeCode || "",
        name: warehouse.name,
        description: warehouse.description || "",
        type: warehouse.type,
        address: warehouse.address || "",
        isDefault: warehouse.isDefault,
        isActive: warehouse.isActive,
        sortOrder: warehouse.sortOrder,
      });
    } else {
      setEditingWarehouse(null);
      setFormData(initialFormData);
    }
    setErrors({});
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditingWarehouse(null);
    setFormData(initialFormData);
    setErrors({});
  };

  const handleChange = (field: string, value: unknown) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    // Il codice è generato automaticamente, non richiede validazione in creazione
    if (!formData.name.trim()) {
      newErrors.name = t("warehouse.locations.dialog.validation.nameRequired");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validate()) return;

    try {
      if (editingWarehouse) {
        // In modifica non inviamo il code (non modificabile)
        const { code: _code, ...updateData } = formData;
        await updateMutation.mutateAsync({
          id: editingWarehouse.id,
          data: updateData,
        });
      } else {
        // In creazione non inviamo il code (generato automaticamente dal backend)
        const { code: _code, ...createData } = formData;
        await createMutation.mutateAsync(createData);
      }
      handleCloseDialog();
    } catch (error) {
      console.error("Errore salvataggio:", error);
    }
  };

  const handleDeleteClick = (warehouse: WarehouseLocationDto) => {
    setWarehouseToDelete(warehouse);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (warehouseToDelete) {
      await deleteMutation.mutateAsync(warehouseToDelete.id);
      setDeleteDialogOpen(false);
      setWarehouseToDelete(null);
    }
  };

  const handleSetDefault = async (warehouse: WarehouseLocationDto) => {
    if (!warehouse.isDefault) {
      await setDefaultMutation.mutateAsync(warehouse.id);
    }
  };

  const getTypeColor = (
    type: WarehouseType,
  ): "primary" | "warning" | "error" | "secondary" | "info" | "default" => {
    switch (type) {
      case WarehouseType.Physical:
        return "primary";
      case WarehouseType.Transit:
        return "warning";
      case WarehouseType.Returns:
        return "error";
      case WarehouseType.Defective:
        return "secondary";
      case WarehouseType.Subcontract:
        return "info";
      default:
        return "default";
    }
  };

  if (error) {
    return (
      <Box p={3}>
        <Alert severity="error">
          {t("warehouse.locations.loadingError", { error: (error as Error).message })}
        </Alert>
      </Box>
    );
  }

  return (
    <Box>
      {/* Header */}
      <Box
        sx={{
          mb: 3,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Typography variant="h5" fontWeight="bold">
          {t("warehouse.locations.title")}
        </Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => handleOpenDialog()}
        >
          {t("warehouse.locations.newWarehouse")}
        </Button>
      </Box>

      {/* Warehouse Cards */}
      <Grid container spacing={3}>
        {isLoading ? (
          Array.from({ length: 4 }).map((_, i) => (
            <Grid key={i} size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
              <Card sx={{ height: "100%" }}>
                <CardContent>
                  <Box
                    sx={{ height: 120, bgcolor: "grey.100", borderRadius: 1 }}
                  />
                </CardContent>
              </Card>
            </Grid>
          ))
        ) : warehouses?.length === 0 ? (
          <Grid size={12}>
            <Paper sx={{ p: 4, textAlign: "center" }}>
              <WarehouseIcon sx={{ fontSize: 48, color: "grey.400", mb: 2 }} />
              <Typography color="text.secondary">
                {t("warehouse.locations.emptyState.title")}
              </Typography>
              <Button
                variant="contained"
                startIcon={<AddIcon />}
                onClick={() => handleOpenDialog()}
                sx={{ mt: 2 }}
              >
                {t("warehouse.locations.emptyState.action")}
              </Button>
            </Paper>
          </Grid>
        ) : (
          warehouses?.map((warehouse) => (
            <Grid key={warehouse.id} size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
              <Card
                sx={{
                  height: "100%",
                  display: "flex",
                  flexDirection: "column",
                  position: "relative",
                  opacity: warehouse.isActive ? 1 : 0.6,
                }}
              >
                {warehouse.isDefault && (
                  <Tooltip title={t("warehouse.locations.card.default")}>
                    <StarIcon
                      sx={{
                        position: "absolute",
                        top: 8,
                        right: 8,
                        color: "warning.main",
                      }}
                    />
                  </Tooltip>
                )}
                <CardContent sx={{ flexGrow: 1 }}>
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      gap: 1,
                      mb: 2,
                    }}
                  >
                    <WarehouseIcon color="primary" />
                    <Typography variant="h6" component="div">
                      {warehouse.code}
                    </Typography>
                  </Box>
                  <Typography variant="body1" fontWeight="medium" gutterBottom>
                    {warehouse.name}
                  </Typography>
                  {warehouse.description && (
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      gutterBottom
                    >
                      {warehouse.description}
                    </Typography>
                  )}
                  <Box
                    sx={{ mt: 2, display: "flex", gap: 1, flexWrap: "wrap" }}
                  >
                    <Chip
                      label={t(`warehouse.warehouseType.${WarehouseType[warehouse.type]}`)}
                      size="small"
                      color={getTypeColor(warehouse.type)}
                    />
                    {!warehouse.isActive && (
                      <Chip label={t("warehouse.locations.card.inactive")} size="small" color="default" />
                    )}
                  </Box>
                  {warehouse.address && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      display="block"
                      sx={{ mt: 1 }}
                    >
                      {warehouse.address}
                    </Typography>
                  )}
                </CardContent>
                <CardActions>
                  <Tooltip title={t("warehouse.locations.card.setDefault")}>
                    <IconButton
                      size="small"
                      onClick={() => handleSetDefault(warehouse)}
                      disabled={
                        warehouse.isDefault || setDefaultMutation.isPending
                      }
                    >
                      {warehouse.isDefault ? (
                        <StarIcon color="warning" />
                      ) : (
                        <StarBorderIcon />
                      )}
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={t("warehouse.locations.card.edit")}>
                    <IconButton
                      size="small"
                      onClick={() => handleOpenDialog(warehouse)}
                    >
                      <EditIcon />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={t("warehouse.locations.card.delete")}>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteClick(warehouse)}
                      disabled={warehouse.isDefault}
                    >
                      <DeleteIcon />
                    </IconButton>
                  </Tooltip>
                </CardActions>
              </Card>
            </Grid>
          ))
        )}
      </Grid>

      {/* Create/Edit Dialog */}
      <Dialog
        open={dialogOpen}
        onClose={handleCloseDialog}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {editingWarehouse ? t("warehouse.locations.dialog.editTitle") : t("warehouse.locations.dialog.createTitle")}
        </DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12, sm: 3 }}>
              <TextField
                fullWidth
                label={t("warehouse.locations.dialog.fields.code")}
                value={
                  editingWarehouse ? formData.code : t("warehouse.locations.dialog.helpers.generatedOnSave")
                }
                disabled
                helperText={
                  editingWarehouse
                    ? t("warehouse.locations.dialog.helpers.generatedAutomatically")
                    : t("warehouse.locations.dialog.helpers.willBeAssigned")
                }
                InputProps={{
                  readOnly: true,
                }}
                sx={
                  !editingWarehouse
                    ? {
                      "& .MuiInputBase-input.Mui-disabled": {
                        fontStyle: "italic",
                        color: "text.secondary",
                      },
                    }
                    : undefined
                }
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 3 }}>
              <TextField
                fullWidth
                label={t("warehouse.locations.dialog.fields.alternativeCode")}
                value={formData.alternativeCode}
                onChange={(e) =>
                  handleChange("alternativeCode", e.target.value)
                }
                helperText={t("warehouse.locations.dialog.helpers.optional")}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label={t("warehouse.locations.dialog.fields.name")}
                value={formData.name}
                onChange={(e) => handleChange("name", e.target.value)}
                error={!!errors.name}
                helperText={errors.name}
                required
              />
            </Grid>
            <Grid size={12}>
              <TextField
                fullWidth
                label={t("warehouse.locations.dialog.fields.description")}
                value={formData.description}
                onChange={(e) => handleChange("description", e.target.value)}
                multiline
                rows={2}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <FormControl fullWidth>
                <InputLabel>{t("warehouse.locations.dialog.fields.type")}</InputLabel>
                <Select
                  value={formData.type}
                  label={t("warehouse.locations.dialog.fields.type")}
                  onChange={(e) => handleChange("type", e.target.value)}
                >
                  {Object.entries(warehouseTypeLabels).map(([value]) => (
                    <MenuItem key={value} value={parseInt(value, 10)}>
                      {t(`warehouse.warehouseType.${WarehouseType[parseInt(value, 10)]}`)}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label={t("warehouse.locations.dialog.fields.address")}
                value={formData.address}
                onChange={(e) => handleChange("address", e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.isDefault}
                    onChange={(e) =>
                      handleChange("isDefault", e.target.checked)
                    }
                  />
                }
                label={t("warehouse.locations.dialog.fields.isDefault")}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.isActive}
                    onChange={(e) => handleChange("isActive", e.target.checked)}
                  />
                }
                label={t("warehouse.locations.dialog.fields.isActive")}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>{t("warehouse.locations.dialog.actions.cancel")}</Button>
          <Button
            onClick={handleSubmit}
            variant="contained"
            disabled={createMutation.isPending || updateMutation.isPending}
          >
            {createMutation.isPending || updateMutation.isPending
              ? t("warehouse.locations.dialog.actions.saving")
              : t("warehouse.locations.dialog.actions.save")}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>{t("warehouse.locations.deleteDialog.title")}</DialogTitle>
        <DialogContent>
          <Typography>
            <Trans
              i18nKey="warehouse.locations.deleteDialog.content"
              values={{ code: warehouseToDelete?.code, name: warehouseToDelete?.name }}
              components={{ strong: <strong /> }}
            />
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            {t("warehouse.locations.deleteDialog.warning")}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>{t("warehouse.locations.deleteDialog.cancel")}</Button>
          <Button
            onClick={handleDeleteConfirm}
            color="error"
            variant="contained"
            disabled={deleteMutation.isPending}
          >
            {deleteMutation.isPending ? t("warehouse.locations.deleteDialog.deleting") : t("warehouse.locations.deleteDialog.delete")}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
