import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormControlLabel,
  Switch,
  Divider,
  Alert,
  CircularProgress,
  IconButton,
  Card,
  CardMedia,
  Tabs,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  InputAdornment,
} from "@mui/material";
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Upload as UploadIcon,
  Delete as DeleteIcon,
  Image as ImageIcon,
} from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import {
  useArticle,
  useCreateArticle,
  useUpdateArticle,
  useUploadArticleImage,
  useCategoryTree,
  useArticleStockLevels,
  useArticleBatches,
  useArticleSerials,
} from "../hooks";
import {
  ValuationMethod,
  StockManagementType,
  valuationMethodLabels,
  stockManagementTypeLabels,
  formatCurrency,
  formatQuantity,
  formatDate,
  CreateArticleDto,
  UpdateArticleDto,
  StockLevelDto,
  BatchDto,
  SerialDto,
} from "../types";

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
    </div>
  );
}

export default function ArticleFormPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const isNew = !id || id === "new";
  const articleId = isNew ? undefined : parseInt(id, 10);

  const [tabValue, setTabValue] = useState(0);
  const [formData, setFormData] = useState({
    code: "",
    alternativeCode: "",
    description: "",
    shortDescription: "",
    categoryId: undefined as number | undefined,
    unitOfMeasure: "PZ",
    barcode: "",
    minimumStock: 0,
    maximumStock: 0,
    reorderPoint: 0,
    reorderQuantity: 0,
    standardCost: 0,
    stockManagement: StockManagementType.Standard,
    valuationMethod: ValuationMethod.WeightedAverage,
    isBatchManaged: false,
    isSerialManaged: false,
    hasExpiry: false,
    expiryWarningDays: 30,
    isActive: true,
    notes: "",
  });
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const { data: article, isLoading: loadingArticle } = useArticle(articleId);
  const { data: categoryTree } = useCategoryTree();
  const { data: stockLevels } = useArticleStockLevels(articleId);
  const { data: batches } = useArticleBatches(articleId);
  const { data: serials } = useArticleSerials(articleId);

  const createMutation = useCreateArticle();
  const updateMutation = useUpdateArticle();
  const uploadImageMutation = useUploadArticleImage();

  // Flatten category tree
  const flatCategories = React.useMemo(() => {
    const result: { id: number; name: string; level: number }[] = [];
    const flatten = (categories: typeof categoryTree, level = 0) => {
      if (!categories) return;
      for (const cat of categories) {
        result.push({ id: cat.id, name: cat.name, level });
        if (cat.children) flatten(cat.children, level + 1);
      }
    };
    flatten(categoryTree);
    return result;
  }, [categoryTree]);

  // Load article data
  useEffect(() => {
    if (article) {
      setFormData({
        code: article.code,
        alternativeCode: article.alternativeCode || "",
        description: article.description,
        shortDescription: article.shortDescription || "",
        categoryId: article.categoryId,
        unitOfMeasure: article.unitOfMeasure,
        barcode: article.barcode || "",
        minimumStock: article.minimumStock || 0,
        maximumStock: article.maximumStock || 0,
        reorderPoint: article.reorderPoint || 0,
        reorderQuantity: article.reorderQuantity || 0,
        standardCost: article.standardCost || 0,
        stockManagement: article.stockManagement,
        valuationMethod:
          article.valuationMethod || ValuationMethod.WeightedAverage,
        isBatchManaged: article.isBatchManaged,
        isSerialManaged: article.isSerialManaged,
        hasExpiry: article.hasExpiry,
        expiryWarningDays: article.expiryWarningDays || 30,
        isActive: article.isActive,
        notes: article.notes || "",
      });
      if (article.hasImage) {
        setImagePreview(`/api/warehouse/articles/${article.id}/image`);
      }
    }
  }, [article]);

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

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setImageFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleRemoveImage = () => {
    setImageFile(null);
    setImagePreview(null);
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    // Il codice è generato automaticamente, non richiede validazione in creazione
    if (!isNew && !formData.code.trim()) {
      newErrors.code = t("warehouse.articleForm.validation.codeRequired");
    }
    if (!formData.description.trim()) {
      newErrors.description = t("warehouse.articleForm.validation.descriptionRequired");
    }
    if (!formData.unitOfMeasure.trim()) {
      newErrors.unitOfMeasure = t("warehouse.articleForm.validation.uomRequired");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    try {
      let savedId: number;
      if (isNew) {
        const createData: CreateArticleDto = {
          // code è generato automaticamente dal backend
          description: formData.description,
          shortDescription: formData.shortDescription || undefined,
          alternativeCode: formData.alternativeCode || undefined,
          categoryId: formData.categoryId,
          unitOfMeasure: formData.unitOfMeasure,
          barcode: formData.barcode || undefined,
          minimumStock: formData.minimumStock,
          maximumStock: formData.maximumStock,
          reorderPoint: formData.reorderPoint,
          reorderQuantity: formData.reorderQuantity,
          standardCost: formData.standardCost,
          stockManagement: formData.stockManagement,
          valuationMethod: formData.valuationMethod,
          isBatchManaged: formData.isBatchManaged,
          isSerialManaged: formData.isSerialManaged,
          hasExpiry: formData.hasExpiry,
          expiryWarningDays: formData.expiryWarningDays,
          notes: formData.notes || undefined,
        };
        const result = await createMutation.mutateAsync(createData);
        savedId = result.id;
      } else {
        const updateData: UpdateArticleDto = {
          // code non modificabile
          description: formData.description,
          shortDescription: formData.shortDescription || undefined,
          alternativeCode: formData.alternativeCode || undefined,
          categoryId: formData.categoryId,
          unitOfMeasure: formData.unitOfMeasure,
          barcode: formData.barcode || undefined,
          minimumStock: formData.minimumStock,
          maximumStock: formData.maximumStock,
          reorderPoint: formData.reorderPoint,
          reorderQuantity: formData.reorderQuantity,
          standardCost: formData.standardCost,
          stockManagement: formData.stockManagement,
          valuationMethod: formData.valuationMethod,
          isBatchManaged: formData.isBatchManaged,
          isSerialManaged: formData.isSerialManaged,
          hasExpiry: formData.hasExpiry,
          expiryWarningDays: formData.expiryWarningDays,
          isActive: formData.isActive,
          notes: formData.notes || undefined,
        };
        await updateMutation.mutateAsync({ id: articleId!, data: updateData });
        savedId = articleId!;
      }

      // Upload image if selected
      if (imageFile) {
        await uploadImageMutation.mutateAsync({ id: savedId, file: imageFile });
      }

      navigate(`/warehouse/articles/${savedId}`);
    } catch (error) {
      console.error("Errore salvataggio:", error);
    }
  };

  const isPending =
    createMutation.isPending ||
    updateMutation.isPending ||
    uploadImageMutation.isPending;

  if (!isNew && loadingArticle) {
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        minHeight={400}
      >
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      {/* Header */}
      <Box sx={{ mb: 3, display: "flex", alignItems: "center", gap: 2 }}>
        <IconButton onClick={() => navigate(-1)}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h5" fontWeight="bold">
          {isNew ? t("warehouse.articleForm.titleNew") : t("warehouse.articleForm.titleEdit", { code: article?.code })}
        </Typography>
      </Box>

      {(createMutation.error || updateMutation.error) && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {t("warehouse.articleForm.errors.saveError", { error: ((createMutation.error || updateMutation.error) as Error).message })}
        </Alert>
      )}

      {!isNew && (
        <Box sx={{ borderBottom: 1, borderColor: "divider", mb: 3 }}>
          <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)}>
            <Tab label={t("warehouse.articleForm.tabs.general")} />
            <Tab label={t("warehouse.articleForm.tabs.stock")} />
            {article?.isBatchManaged && <Tab label={t("warehouse.articleForm.tabs.batches")} />}
            {article?.isSerialManaged && <Tab label={t("warehouse.articleForm.tabs.serials")} />}
          </Tabs>
        </Box>
      )}

      <TabPanel value={tabValue} index={0}>
        <form onSubmit={handleSubmit}>
          <Grid container spacing={3}>
            {/* Left Column - Form */}
            <Grid size={{ xs: 12, md: 8 }}>
              <Paper sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  {t("warehouse.articleForm.sections.basicInfo")}
                </Typography>
                <Grid container spacing={2}>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.code")}
                      value={
                        isNew ? t("warehouse.articleForm.helpers.generatedOnSave") : formData.code
                      }
                      disabled
                      helperText={
                        isNew
                          ? t("warehouse.articleForm.helpers.willBeGenerated")
                          : t("warehouse.articleForm.helpers.generatedAutomatically")
                      }
                      InputProps={{
                        readOnly: true,
                      }}
                      sx={
                        isNew
                          ? {
                            "& .MuiInputBase-input.Mui-disabled": {
                              fontStyle: "italic",
                              color: "text.secondary",
                            },
                          }
                          : undefined
                      }
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.alternativeCode")}
                      value={formData.alternativeCode}
                      onChange={(e) =>
                        handleChange("alternativeCode", e.target.value)
                      }
                      helperText={t("warehouse.articleForm.helpers.optional")}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.description")}
                      value={formData.description}
                      onChange={(e) =>
                        handleChange("description", e.target.value)
                      }
                      error={!!errors.description}
                      helperText={errors.description}
                      required
                    />
                  </Grid>
                  <Grid size={12}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.shortDescription")}
                      value={formData.shortDescription}
                      onChange={(e) =>
                        handleChange("shortDescription", e.target.value)
                      }
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 6 }}>
                    <FormControl fullWidth>
                      <InputLabel>{t("warehouse.articleForm.fields.category")}</InputLabel>
                      <Select
                        value={formData.categoryId || ""}
                        label={t("warehouse.articleForm.fields.category")}
                        onChange={(e) =>
                          handleChange(
                            "categoryId",
                            e.target.value || undefined,
                          )
                        }
                      >
                        <MenuItem value="">
                          <em>{t("warehouse.articleForm.options.noCategory")}</em>
                        </MenuItem>
                        {flatCategories.map((cat) => (
                          <MenuItem key={cat.id} value={cat.id}>
                            {"—".repeat(cat.level)} {cat.name}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.uom")}
                      value={formData.unitOfMeasure}
                      onChange={(e) =>
                        handleChange("unitOfMeasure", e.target.value)
                      }
                      error={!!errors.unitOfMeasure}
                      helperText={errors.unitOfMeasure}
                      required
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.barcode")}
                      value={formData.barcode}
                      onChange={(e) => handleChange("barcode", e.target.value)}
                    />
                  </Grid>
                </Grid>

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

                <Typography variant="h6" gutterBottom>
                  {t("warehouse.articleForm.sections.stockLevels")}
                </Typography>
                <Grid container spacing={2}>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.minStock")}
                      type="number"
                      value={formData.minimumStock}
                      onChange={(e) =>
                        handleChange(
                          "minimumStock",
                          parseFloat(e.target.value) || 0,
                        )
                      }
                      InputProps={{ inputProps: { min: 0, step: 0.01 } }}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.maxStock")}
                      type="number"
                      value={formData.maximumStock}
                      onChange={(e) =>
                        handleChange(
                          "maximumStock",
                          parseFloat(e.target.value) || 0,
                        )
                      }
                      InputProps={{ inputProps: { min: 0, step: 0.01 } }}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.reorderPoint")}
                      type="number"
                      value={formData.reorderPoint}
                      onChange={(e) =>
                        handleChange(
                          "reorderPoint",
                          parseFloat(e.target.value) || 0,
                        )
                      }
                      InputProps={{ inputProps: { min: 0, step: 0.01 } }}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 3 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.reorderQuantity")}
                      type="number"
                      value={formData.reorderQuantity}
                      onChange={(e) =>
                        handleChange(
                          "reorderQuantity",
                          parseFloat(e.target.value) || 0,
                        )
                      }
                      InputProps={{ inputProps: { min: 0, step: 0.01 } }}
                    />
                  </Grid>
                </Grid>

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

                <Typography variant="h6" gutterBottom>
                  {t("warehouse.articleForm.sections.costs")}
                </Typography>
                <Grid container spacing={2}>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <TextField
                      fullWidth
                      label={t("warehouse.articleForm.fields.standardCost")}
                      type="number"
                      value={formData.standardCost}
                      onChange={(e) =>
                        handleChange(
                          "standardCost",
                          parseFloat(e.target.value) || 0,
                        )
                      }
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">€</InputAdornment>
                        ),
                        inputProps: { min: 0, step: 0.01 },
                      }}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <FormControl fullWidth>
                      <InputLabel>{t("warehouse.articleForm.fields.stockManagement")}</InputLabel>
                      <Select
                        value={formData.stockManagement}
                        label={t("warehouse.articleForm.fields.stockManagement")}
                        onChange={(e) =>
                          handleChange("stockManagement", e.target.value)
                        }
                      >
                        {Object.entries(stockManagementTypeLabels).map(
                          ([value]) => (
                            <MenuItem key={value} value={parseInt(value, 10)}>
                              {t(`warehouse.stockManagementType.${StockManagementType[parseInt(value, 10)]}`)}
                            </MenuItem>
                          ),
                        )}
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <FormControl fullWidth>
                      <InputLabel>{t("warehouse.articleForm.fields.valuationMethod")}</InputLabel>
                      <Select
                        value={formData.valuationMethod}
                        label={t("warehouse.articleForm.fields.valuationMethod")}
                        onChange={(e) =>
                          handleChange("valuationMethod", e.target.value)
                        }
                      >
                        {Object.entries(valuationMethodLabels).map(
                          ([value]) => (
                            <MenuItem key={value} value={parseInt(value, 10)}>
                              {t(`warehouse.valuationMethod.${ValuationMethod[parseInt(value, 10)]}`)}
                            </MenuItem>
                          ),
                        )}
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>

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

                <Typography variant="h6" gutterBottom>
                  {t("warehouse.articleForm.sections.traceability")}
                </Typography>
                <Grid container spacing={2}>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={formData.isBatchManaged}
                          onChange={(e) =>
                            handleChange("isBatchManaged", e.target.checked)
                          }
                          disabled={!isNew && article?.isBatchManaged}
                        />
                      }
                      label={t("warehouse.articleForm.fields.batchManaged")}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={formData.isSerialManaged}
                          onChange={(e) =>
                            handleChange("isSerialManaged", e.target.checked)
                          }
                          disabled={!isNew && article?.isSerialManaged}
                        />
                      }
                      label={t("warehouse.articleForm.fields.serialManaged")}
                    />
                  </Grid>
                  <Grid size={{ xs: 12, sm: 4 }}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={formData.hasExpiry}
                          onChange={(e) =>
                            handleChange("hasExpiry", e.target.checked)
                          }
                        />
                      }
                      label={t("warehouse.articleForm.fields.expiryManaged")}
                    />
                  </Grid>
                  <Grid size={12}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={formData.isActive}
                          onChange={(e) =>
                            handleChange("isActive", e.target.checked)
                          }
                        />
                      }
                      label={t("warehouse.articleForm.fields.active")}
                    />
                  </Grid>
                </Grid>

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

                <TextField
                  fullWidth
                  label={t("warehouse.articleForm.fields.notes")}
                  value={formData.notes}
                  onChange={(e) => handleChange("notes", e.target.value)}
                  multiline
                  rows={3}
                />
              </Paper>
            </Grid>

            {/* Right Column - Image */}
            <Grid size={{ xs: 12, md: 4 }}>
              <Paper sx={{ p: 3 }}>
                <Typography variant="h6" gutterBottom>
                  {t("warehouse.articleForm.sections.image")}
                </Typography>
                {imagePreview ? (
                  <Card sx={{ mb: 2 }}>
                    <CardMedia
                      component="img"
                      image={imagePreview}
                      alt={t("common.preview")}
                      sx={{
                        height: 200,
                        objectFit: "contain",
                        bgcolor: "grey.100",
                      }}
                    />
                  </Card>
                ) : (
                  <Box
                    sx={{
                      height: 200,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      bgcolor: "grey.100",
                      borderRadius: 1,
                      mb: 2,
                    }}
                  >
                    <ImageIcon sx={{ fontSize: 64, color: "grey.400" }} />
                  </Box>
                )}
                <Box sx={{ display: "flex", gap: 1 }}>
                  <Button
                    variant="outlined"
                    component="label"
                    startIcon={<UploadIcon />}
                    fullWidth
                  >
                    {t("warehouse.articleForm.actions.upload")}
                    <input
                      type="file"
                      hidden
                      accept="image/*"
                      onChange={handleImageChange}
                    />
                  </Button>
                  {imagePreview && (
                    <IconButton color="error" onClick={handleRemoveImage}>
                      <DeleteIcon />
                    </IconButton>
                  )}
                </Box>
              </Paper>

              {/* Summary Card (only for existing articles) */}
              {!isNew && article && (
                <Paper sx={{ p: 3, mt: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    {t("warehouse.articleForm.sections.summary")}
                  </Typography>
                  <Box
                    sx={{ display: "flex", flexDirection: "column", gap: 1 }}
                  >
                    <Box
                      sx={{ display: "flex", justifyContent: "space-between" }}
                    >
                      <Typography color="text.secondary">
                        {t("warehouse.articleForm.summary.averageCost")}:
                      </Typography>
                      <Typography fontWeight="medium">
                        {formatCurrency(article.weightedAverageCost || 0)}
                      </Typography>
                    </Box>
                    <Box
                      sx={{ display: "flex", justifyContent: "space-between" }}
                    >
                      <Typography color="text.secondary">
                        {t("warehouse.articleForm.summary.lastPurchase")}:
                      </Typography>
                      <Typography fontWeight="medium">
                        {formatCurrency(article.lastPurchaseCost || 0)}
                      </Typography>
                    </Box>
                  </Box>
                </Paper>
              )}
            </Grid>

            {/* Submit Button */}
            <Grid size={12}>
              <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
                <Button onClick={() => navigate(-1)}>{t("warehouse.articleForm.actions.cancel")}</Button>
                <Button
                  type="submit"
                  variant="contained"
                  startIcon={
                    isPending ? <CircularProgress size={20} /> : <SaveIcon />
                  }
                  disabled={isPending}
                >
                  {isPending ? t("warehouse.articleForm.actions.saving") : t("warehouse.articleForm.actions.save")}
                </Button>
              </Box>
            </Grid>
          </Grid>
        </form>
      </TabPanel>

      {/* Stock Levels Tab */}
      <TabPanel value={tabValue} index={1}>
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            {t("warehouse.articleForm.sections.stockLevels")}
          </Typography>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t("warehouse.articleForm.tables.warehouse")}</TableCell>
                  <TableCell align="right">{t("warehouse.articleForm.tables.quantity")}</TableCell>
                  <TableCell align="right">{t("warehouse.articleForm.tables.reserved")}</TableCell>
                  <TableCell align="right">{t("warehouse.articleForm.tables.available")}</TableCell>
                  <TableCell align="right">{t("warehouse.articleForm.tables.value")}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {!stockLevels || stockLevels.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} align="center">
                      <Typography color="text.secondary">
                        {t("warehouse.articleForm.tables.noStock")}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  stockLevels.map((level: StockLevelDto) => (
                    <TableRow key={level.id}>
                      <TableCell>{level.warehouseName}</TableCell>
                      <TableCell align="right">
                        {formatQuantity(level.quantity)}{" "}
                        {article?.unitOfMeasure}
                      </TableCell>
                      <TableCell align="right">
                        {formatQuantity(level.reservedQuantity)}{" "}
                        {article?.unitOfMeasure}
                      </TableCell>
                      <TableCell align="right">
                        {formatQuantity(level.availableQuantity)}{" "}
                        {article?.unitOfMeasure}
                      </TableCell>
                      <TableCell align="right">
                        {formatCurrency(level.stockValue)}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      </TabPanel>

      {/* Batches Tab */}
      {article?.isBatchManaged && (
        <TabPanel value={tabValue} index={2}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              {t("warehouse.articleForm.tabs.batches")}
            </Typography>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t("warehouse.articleForm.tables.batchNumber")}</TableCell>
                    <TableCell align="right">{t("warehouse.articleForm.tables.quantity")}</TableCell>
                    <TableCell>{t("warehouse.articleForm.tables.expiryDate")}</TableCell>
                    <TableCell>{t("warehouse.articleForm.tables.status")}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {!batches || batches.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} align="center">
                        <Typography color="text.secondary">
                          {t("warehouse.articleForm.tables.noBatches")}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    batches.map((batch: BatchDto) => (
                      <TableRow key={batch.id}>
                        <TableCell>{batch.batchNumber}</TableCell>
                        <TableCell align="right">
                          {formatQuantity(batch.currentQuantity)}{" "}
                          {article?.unitOfMeasure}
                        </TableCell>
                        <TableCell>
                          {batch.expiryDate
                            ? formatDate(batch.expiryDate)
                            : "-"}
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={batch.isExpired ? t("warehouse.articleForm.status.expired") : t("warehouse.articleForm.status.available")}
                            size="small"
                            color={batch.isExpired ? "error" : "success"}
                          />
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </TabPanel>
      )}

      {/* Serials Tab */}
      {article?.isSerialManaged && (
        <TabPanel value={tabValue} index={article?.isBatchManaged ? 3 : 2}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              {t("warehouse.articleForm.tabs.serials")}
            </Typography>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t("warehouse.articleForm.tables.serialNumber")}</TableCell>
                    <TableCell>{t("warehouse.articleForm.tables.warehouse")}</TableCell>
                    <TableCell>{t("warehouse.articleForm.tables.lot")}</TableCell>
                    <TableCell>{t("warehouse.articleForm.tables.status")}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {!serials || serials.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} align="center">
                        <Typography color="text.secondary">
                          {t("warehouse.articleForm.tables.noSerials")}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    serials.map((serial: SerialDto) => (
                      <TableRow key={serial.id}>
                        <TableCell>{serial.serialNumber}</TableCell>
                        <TableCell>
                          {serial.currentWarehouseName || "-"}
                        </TableCell>
                        <TableCell>{serial.batchNumber || "-"}</TableCell>
                        <TableCell>
                          <Chip
                            label={
                              serial.status === 0
                                ? t("warehouse.articleForm.status.available")
                                : t("warehouse.articleForm.status.unavailable")
                            }
                            size="small"
                            color={serial.status === 0 ? "success" : "default"}
                          />
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </TabPanel>
      )}
    </Box>
  );
}
