import React, { useState } from "react";
import {
  Box,
  Paper,
  Typography,
  TextField,
  InputAdornment,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Alert,
  Chip,
  FormControlLabel,
  Switch,
  Button,
  Card,
  CardContent,
} from "@mui/material";
import {
  Search as SearchIcon,
  Clear as ClearIcon,
  Warning as WarningIcon,
  TrendingUp as TrendingUpIcon,
} from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { useStockLevels, useWarehouses, useCategoryTree } from "../hooks";
import { useStockCalculations } from "../hooks/useStockCalculations";
import { useWarehouseNavigation } from "../hooks/useWarehouseNavigation";
import { StockLevelDto, formatCurrency, formatQuantity } from "../types";

export default function StockLevelsPage() {
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const [warehouseId, setWarehouseId] = useState<number | "">("");
  const [categoryId, setCategoryId] = useState<number | "">("");
  const [lowStockOnly, setLowStockOnly] = useState(false);

  const nav = useWarehouseNavigation();

  const {
    data: stockLevels,
    isLoading,
    error,
  } = useStockLevels({
    warehouseId: warehouseId || undefined,
    categoryId: categoryId || undefined,
    onlyLowStock: lowStockOnly || undefined,
  });

  const { data: warehouses } = useWarehouses();
  const { data: categoryTree } = useCategoryTree();
  const { summary } = useStockCalculations(stockLevels);

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

  // Filter by search
  const filteredLevels = React.useMemo(() => {
    if (!stockLevels) return [];
    if (!search) return stockLevels;
    const lower = search.toLowerCase();
    return stockLevels.filter(
      (l) =>
        l.articleCode?.toLowerCase().includes(lower) ||
        l.articleDescription?.toLowerCase().includes(lower),
    );
  }, [stockLevels, search]);

  const columns: GridColDef[] = [
    {
      field: "articleCode",
      headerName: t("warehouse.stockLevels.columns.code"),
      width: 120,
      renderCell: (params: GridRenderCellParams<StockLevelDto>) => (
        <Typography variant="body2" fontWeight="medium">
          {params.value}
        </Typography>
      ),
    },
    {
      field: "articleDescription",
      headerName: t("warehouse.stockLevels.columns.article"),
      flex: 1,
      minWidth: 200,
    },
    {
      field: "warehouseName",
      headerName: t("warehouse.stockLevels.columns.warehouse"),
      width: 150,
    },
    {
      field: "categoryName",
      headerName: t("warehouse.stockLevels.columns.category"),
      width: 140,
    },
    {
      field: "quantity",
      headerName: t("warehouse.stockLevels.columns.quantity"),
      width: 120,
      align: "right",
      renderCell: (params: GridRenderCellParams<StockLevelDto>) => {
        const qty = params.value || 0;
        const isLow = params.row.isLowStock;
        return (
          <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
            {isLow && <WarningIcon color="warning" sx={{ fontSize: 16 }} />}
            <Chip
              label={formatQuantity(qty)}
              size="small"
              color={qty <= 0 ? "error" : isLow ? "warning" : "default"}
            />
          </Box>
        );
      },
    },
    {
      field: "reservedQuantity",
      headerName: t("warehouse.stockLevels.columns.reserved"),
      width: 100,
      align: "right",
      renderCell: (params: GridRenderCellParams<StockLevelDto>) =>
        formatQuantity(params.value || 0),
    },
    {
      field: "availableQuantity",
      headerName: t("warehouse.stockLevels.columns.available"),
      width: 110,
      align: "right",
      renderCell: (params: GridRenderCellParams<StockLevelDto>) => {
        const available =
          params.row.availableQuantity ||
          params.row.quantity - params.row.reservedQuantity;
        return (
          <Typography
            fontWeight="medium"
            color={available <= 0 ? "error.main" : "text.primary"}
          >
            {formatQuantity(available)}
          </Typography>
        );
      },
    },
    {
      field: "unitCost",
      headerName: t("warehouse.stockLevels.columns.averageCost"),
      width: 120,
      align: "right",
      renderCell: (params: GridRenderCellParams<StockLevelDto>) =>
        formatCurrency(params.value || 0),
    },
    {
      field: "stockValue",
      headerName: t("warehouse.stockLevels.columns.value"),
      width: 130,
      align: "right",
      renderCell: (params: GridRenderCellParams<StockLevelDto>) => (
        <Typography fontWeight="medium">
          {formatCurrency(params.value || 0)}
        </Typography>
      ),
    },
  ];

  if (error) {
    return (
      <Box p={3}>
        <Alert severity="error">{t("warehouse.stockLevels.error", { 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.stockLevels.title")}
        </Typography>
        <Button
          variant="outlined"
          startIcon={<TrendingUpIcon />}
          onClick={nav.goToValuation}
        >
          {t("warehouse.stockLevels.valuation")}
        </Button>
      </Box>

      {/* Summary Cards */}
      <Grid container spacing={2} sx={{ mb: 3 }}>
        <Grid size={{ xs: 6, sm: 3 }}>
          <Card>
            <CardContent sx={{ py: 2 }}>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.stockLevels.summary.articles")}
              </Typography>
              <Typography variant="h5" fontWeight="bold">
                {summary.articleCount}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 6, sm: 3 }}>
          <Card>
            <CardContent sx={{ py: 2 }}>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.stockLevels.summary.totalQuantity")}
              </Typography>
              <Typography variant="h5" fontWeight="bold">
                {formatQuantity(summary.totalQuantity)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 6, sm: 3 }}>
          <Card>
            <CardContent sx={{ py: 2 }}>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.stockLevels.summary.totalValue")}
              </Typography>
              <Typography variant="h5" fontWeight="bold" color="success.main">
                {formatCurrency(summary.totalValue)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 6, sm: 3 }}>
          <Card>
            <CardContent sx={{ py: 2 }}>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.stockLevels.summary.lowStock")}
              </Typography>
              <Typography variant="h5" fontWeight="bold" color="warning.main">
                {summary.lowStockCount + summary.outOfStockCount}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Filters */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Grid container spacing={2} alignItems="center">
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <TextField
              fullWidth
              size="small"
              placeholder={t("warehouse.stockLevels.filters.search")}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: search && (
                  <InputAdornment position="end">
                    <IconButton size="small" onClick={() => setSearch("")}>
                      <ClearIcon />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <FormControl fullWidth size="small">
              <InputLabel>{t("warehouse.stockLevels.filters.warehouse")}</InputLabel>
              <Select
                value={warehouseId}
                label={t("warehouse.stockLevels.filters.warehouse")}
                onChange={(e) => setWarehouseId(e.target.value as number | "")}
              >
                <MenuItem value="">
                  <em>{t("warehouse.stockLevels.filters.allWarehouses")}</em>
                </MenuItem>
                {warehouses?.map((w) => (
                  <MenuItem key={w.id} value={w.id}>
                    {w.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <FormControl fullWidth size="small">
              <InputLabel>{t("warehouse.stockLevels.filters.category")}</InputLabel>
              <Select
                value={categoryId}
                label={t("warehouse.stockLevels.filters.category")}
                onChange={(e) => setCategoryId(e.target.value as number | "")}
              >
                <MenuItem value="">
                  <em>{t("warehouse.stockLevels.filters.allCategories")}</em>
                </MenuItem>
                {flatCategories.map((c) => (
                  <MenuItem key={c.id} value={c.id}>
                    {"—".repeat(c.level)} {c.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={lowStockOnly}
                  onChange={(e) => setLowStockOnly(e.target.checked)}
                />
              }
              label={t("warehouse.stockLevels.filters.lowStockOnly")}
            />
          </Grid>
        </Grid>
      </Paper>

      {/* Data Grid */}
      <Paper sx={{ height: 500 }}>
        <DataGrid
          rows={filteredLevels}
          columns={columns}
          loading={isLoading}
          pageSizeOptions={[25, 50, 100]}
          initialState={{
            pagination: { paginationModel: { pageSize: 25 } },
            sorting: { sortModel: [{ field: "articleCode", sort: "asc" }] },
          }}
          onRowDoubleClick={(params) => nav.goToArticle(params.row.articleId)}
          disableRowSelectionOnClick
        />
      </Paper>
    </Box>
  );
}
