import React from "react";
import {
  Box,
  Paper,
  Typography,
  Grid,
  Card,
  CardContent,
  Button,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Chip,
  Divider,
  Skeleton,
  Alert,
} from "@mui/material";
import {
  Inventory as InventoryIcon,
  Warehouse as WarehouseIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  Warning as WarningIcon,
  Schedule as ScheduleIcon,
  ArrowForward as ArrowForwardIcon,
  Add as AddIcon,
  Assessment as AssessmentIcon,
} from "@mui/icons-material";
import {
  useArticles,
  useWarehouses,
  useMovements,
  useStockLevels,
  useExpiringBatches,
} from "../hooks";
import { useWarehouseNavigation } from "../hooks/useWarehouseNavigation";
import {
  MovementStatus,
  MovementType,
  formatCurrency,
  formatQuantity,
  formatDate,
  movementTypeLabels,
  getMovementTypeColor,
} from "../types";

interface StatCardProps {
  title: string;
  value: string | number;
  subtitle?: string;
  icon: React.ReactNode;
  color?: string;
  loading?: boolean;
}

function StatCard({
  title,
  value,
  subtitle,
  icon,
  color = "primary.main",
  loading,
}: StatCardProps) {
  return (
    <Card>
      <CardContent>
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
          }}
        >
          <Box>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              {title}
            </Typography>
            {loading ? (
              <Skeleton width={100} height={40} />
            ) : (
              <Typography variant="h4" fontWeight="bold" sx={{ color }}>
                {value}
              </Typography>
            )}
            {subtitle && (
              <Typography variant="caption" color="text.secondary">
                {subtitle}
              </Typography>
            )}
          </Box>
          <Box
            sx={{
              p: 1,
              borderRadius: 2,
              bgcolor: `${color}15`,
              color,
            }}
          >
            {icon}
          </Box>
        </Box>
      </CardContent>
    </Card>
  );
}

export default function WarehouseDashboard() {
  const nav = useWarehouseNavigation();

  const { data: articles, isLoading: loadingArticles } = useArticles({
    isActive: true,
  });
  const { data: warehouses, isLoading: loadingWarehouses } = useWarehouses({
    active: true,
  });
  const { data: stockLevels, isLoading: loadingStock } = useStockLevels();
  const { data: recentMovements, isLoading: loadingMovements } = useMovements();
  const { data: expiringBatches } = useExpiringBatches(30);

  // Calculate statistics
  const totalArticles = articles?.length || 0;
  const totalWarehouses = warehouses?.length || 0;

  const stockStats = React.useMemo(() => {
    if (!stockLevels) return { totalValue: 0, lowStock: 0, outOfStock: 0 };

    let totalValue = 0;
    let lowStock = 0;
    let outOfStock = 0;

    for (const level of stockLevels) {
      totalValue += level.stockValue || 0;
      if (level.quantity <= 0) outOfStock++;
      else if (level.isLowStock) lowStock++;
    }

    return { totalValue, lowStock, outOfStock };
  }, [stockLevels]);

  // Recent movements (last 10)
  const lastMovements = React.useMemo(() => {
    if (!recentMovements) return [];
    return recentMovements
      .filter((m) => m.status === MovementStatus.Confirmed)
      .slice(0, 10);
  }, [recentMovements]);

  // Pending movements (drafts)
  const pendingMovements = React.useMemo(() => {
    if (!recentMovements) return [];
    return recentMovements.filter((m) => m.status === MovementStatus.Draft);
  }, [recentMovements]);

  // Low stock articles
  const lowStockArticles = React.useMemo(() => {
    if (!stockLevels || !articles) return [];
    const lowIds = new Set(
      stockLevels
        .filter((l) => l.isLowStock || l.quantity <= 0)
        .map((l) => l.articleId),
    );
    return articles.filter((a) => lowIds.has(a.id)).slice(0, 5);
  }, [stockLevels, articles]);

  // Get stock quantity for an article
  const getArticleStock = (articleId: number) => {
    if (!stockLevels) return 0;
    return stockLevels
      .filter((l) => l.articleId === articleId)
      .reduce((sum, l) => sum + l.quantity, 0);
  };

  return (
    <Box>
      {/* Header */}
      {/* Actions */}
      <Box
        sx={{
          mb: 4,
          display: "flex",
          justifyContent: "flex-end",
          alignItems: "center",
          gap: 1
        }}
      >
        <Button
          variant="outlined"
          startIcon={<AddIcon />}
          onClick={nav.goToNewInbound}
        >
          Nuovo Carico
        </Button>
        <Button
          variant="contained"
          startIcon={<AssessmentIcon />}
          onClick={nav.goToStockLevels}
        >
          Giacenze
        </Button>
      </Box>

      {/* Stats Cards */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Articoli Attivi"
            value={totalArticles}
            icon={<InventoryIcon />}
            loading={loadingArticles}
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Magazzini"
            value={totalWarehouses}
            icon={<WarehouseIcon />}
            loading={loadingWarehouses}
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Valore Totale"
            value={formatCurrency(stockStats.totalValue)}
            icon={<TrendingUpIcon />}
            color="success.main"
            loading={loadingStock}
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Sotto Scorta"
            value={stockStats.lowStock + stockStats.outOfStock}
            subtitle={`${stockStats.outOfStock} esauriti`}
            icon={<WarningIcon />}
            color="warning.main"
            loading={loadingStock}
          />
        </Grid>
      </Grid>

      {/* Main Content */}
      <Grid container spacing={3}>
        {/* Recent Movements */}
        <Grid size={{ xs: 12, md: 6 }}>
          <Paper sx={{ p: 3, height: "100%" }}>
            <Box
              sx={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                mb: 2,
              }}
            >
              <Typography variant="h6">Ultimi Movimenti</Typography>
              <Button
                size="small"
                endIcon={<ArrowForwardIcon />}
                onClick={nav.goToMovements}
              >
                Vedi tutti
              </Button>
            </Box>
            {loadingMovements ? (
              <Box>
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} height={60} sx={{ mb: 1 }} />
                ))}
              </Box>
            ) : lastMovements.length === 0 ? (
              <Typography color="text.secondary" textAlign="center" py={4}>
                Nessun movimento recente
              </Typography>
            ) : (
              <List disablePadding>
                {lastMovements.map((movement, index) => (
                  <React.Fragment key={movement.id}>
                    <ListItem
                      sx={{ px: 0, cursor: "pointer" }}
                      onClick={() => nav.goToMovement(movement.id)}
                    >
                      <ListItemIcon>
                        {movement.type === MovementType.Inbound ? (
                          <TrendingUpIcon color="success" />
                        ) : movement.type === MovementType.Outbound ? (
                          <TrendingDownIcon color="error" />
                        ) : (
                          <WarehouseIcon color="primary" />
                        )}
                      </ListItemIcon>
                      <ListItemText
                        primary={
                          <Box
                            sx={{
                              display: "flex",
                              alignItems: "center",
                              gap: 1,
                            }}
                          >
                            <Typography variant="body2" fontWeight="medium">
                              {movement.documentNumber || `MOV-${movement.id}`}
                            </Typography>
                            <Chip
                              label={movementTypeLabels[movement.type]}
                              size="small"
                              color={
                                getMovementTypeColor(movement.type) as
                                | "success"
                                | "error"
                                | "info"
                                | "warning"
                                | "default"
                              }
                            />
                          </Box>
                        }
                        secondary={`${movement.sourceWarehouseName || movement.destinationWarehouseName || "-"} - ${formatDate(movement.movementDate)}`}
                      />
                      <Typography variant="body2" color="text.secondary">
                        {formatQuantity(movement.lineCount)} righe
                      </Typography>
                    </ListItem>
                    {index < lastMovements.length - 1 && <Divider />}
                  </React.Fragment>
                ))}
              </List>
            )}
          </Paper>
        </Grid>

        {/* Alerts Section */}
        <Grid size={{ xs: 12, md: 6 }}>
          <Grid container spacing={3}>
            {/* Pending Movements */}
            {pendingMovements.length > 0 && (
              <Grid size={12}>
                <Alert
                  severity="info"
                  icon={<ScheduleIcon />}
                  action={
                    <Button size="small" onClick={nav.goToMovements}>
                      Gestisci
                    </Button>
                  }
                >
                  <strong>{pendingMovements.length}</strong> movimenti in bozza
                  da confermare
                </Alert>
              </Grid>
            )}

            {/* Expiring Batches */}
            {expiringBatches && expiringBatches.length > 0 && (
              <Grid size={12}>
                <Alert
                  severity="warning"
                  icon={<ScheduleIcon />}
                  action={
                    <Button size="small" onClick={nav.goToBatches}>
                      Visualizza
                    </Button>
                  }
                >
                  <strong>{expiringBatches.length}</strong> lotti in scadenza
                  nei prossimi 30 giorni
                </Alert>
              </Grid>
            )}

            {/* Low Stock Articles */}
            <Grid size={12}>
              <Paper sx={{ p: 3 }}>
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    mb: 2,
                  }}
                >
                  <Typography variant="h6">Articoli Sotto Scorta</Typography>
                  <Button
                    size="small"
                    endIcon={<ArrowForwardIcon />}
                    onClick={nav.goToArticles}
                  >
                    Vedi tutti
                  </Button>
                </Box>
                {lowStockArticles.length === 0 ? (
                  <Typography color="text.secondary" textAlign="center" py={2}>
                    Nessun articolo sotto scorta
                  </Typography>
                ) : (
                  <List disablePadding>
                    {lowStockArticles.map((article, index) => {
                      const currentStock = getArticleStock(article.id);
                      return (
                        <React.Fragment key={article.id}>
                          <ListItem
                            sx={{ px: 0, cursor: "pointer" }}
                            onClick={() => nav.goToArticle(article.id)}
                          >
                            <ListItemIcon>
                              <WarningIcon color="warning" />
                            </ListItemIcon>
                            <ListItemText
                              primary={article.description}
                              secondary={article.code}
                            />
                            <Chip
                              label={`${formatQuantity(currentStock)} ${article.unitOfMeasure}`}
                              size="small"
                              color={currentStock <= 0 ? "error" : "warning"}
                            />
                          </ListItem>
                          {index < lowStockArticles.length - 1 && <Divider />}
                        </React.Fragment>
                      );
                    })}
                  </List>
                )}
              </Paper>
            </Grid>
          </Grid>
        </Grid>

        {/* Quick Actions */}
        <Grid size={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              Azioni Rapide
            </Typography>
            <Grid container spacing={2}>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToNewInbound}
                >
                  <CardContent>
                    <TrendingUpIcon color="success" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Carico</Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToNewOutbound}
                >
                  <CardContent>
                    <TrendingDownIcon color="error" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Scarico</Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToNewTransfer}
                >
                  <CardContent>
                    <WarehouseIcon color="primary" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Trasferimento</Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToNewArticle}
                >
                  <CardContent>
                    <InventoryIcon color="info" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Nuovo Articolo</Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToNewInventory}
                >
                  <CardContent>
                    <AssessmentIcon color="secondary" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Inventario</Typography>
                  </CardContent>
                </Card>
              </Grid>
              <Grid size={{ xs: 6, sm: 4, md: 2 }}>
                <Card
                  sx={{
                    textAlign: "center",
                    cursor: "pointer",
                    "&:hover": { boxShadow: 3 },
                  }}
                  onClick={nav.goToValuation}
                >
                  <CardContent>
                    <TrendingUpIcon color="warning" sx={{ fontSize: 40 }} />
                    <Typography variant="body2">Valorizzazione</Typography>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>
          </Paper>
        </Grid>
      </Grid>
    </Box>
  );
}
