import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Alert,
  CircularProgress,
  Autocomplete,
  InputAdornment,
  Divider,
  Chip,
  Tooltip,
} from "@mui/material";
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Add as AddIcon,
  Delete as DeleteIcon,
  Check as ConfirmIcon,
  Warning as WarningIcon,
} from "@mui/icons-material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/it";
import {
  useWarehouses,
  useArticles,
  useStockLevels,
  useCreateOutboundMovement,
  useConfirmMovement,
} from "../hooks";
import { ArticleDto, CreateMovementDto, formatQuantity } from "../types";

interface MovementLine {
  id: string;
  article: ArticleDto | null;
  quantity: number;
  notes?: string;
  availableQty?: number;
}

export default function OutboundMovementPage() {
  const navigate = useNavigate();
  const [movementDate, setMovementDate] = useState<Dayjs | null>(dayjs());
  const [warehouseId, setWarehouseId] = useState<number | "">("");
  const [documentNumber, setDocumentNumber] = useState("");
  const [externalReference, setExternalReference] = useState("");
  const [notes, setNotes] = useState("");
  const [lines, setLines] = useState<MovementLine[]>([
    { id: crypto.randomUUID(), article: null, quantity: 1 },
  ]);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const { data: warehouses } = useWarehouses({ active: true });
  const { data: articles } = useArticles({ isActive: true });
  const { data: stockLevels } = useStockLevels({
    warehouseId: warehouseId || undefined,
  });
  const createMutation = useCreateOutboundMovement();
  const confirmMutation = useConfirmMovement();

  // Set default warehouse
  React.useEffect(() => {
    if (warehouses && warehouseId === "") {
      const defaultWarehouse = warehouses.find((w) => w.isDefault);
      if (defaultWarehouse) {
        setWarehouseId(defaultWarehouse.id);
      }
    }
  }, [warehouses, warehouseId]);

  // Get available quantity for an article
  const getAvailableQty = (articleId: number): number => {
    if (!stockLevels) return 0;
    const level = stockLevels.find((l) => l.articleId === articleId);
    return level ? level.availableQuantity : 0;
  };

  const handleAddLine = () => {
    setLines([
      ...lines,
      { id: crypto.randomUUID(), article: null, quantity: 1 },
    ]);
  };

  const handleRemoveLine = (id: string) => {
    if (lines.length > 1) {
      setLines(lines.filter((l) => l.id !== id));
    }
  };

  const handleLineChange = (
    id: string,
    field: keyof MovementLine,
    value: unknown,
  ) => {
    setLines(
      lines.map((l) => {
        if (l.id === id) {
          const updated = { ...l, [field]: value };
          // Update available qty when article changes
          if (field === "article" && value) {
            const article = value as ArticleDto;
            updated.availableQty = getAvailableQty(article.id);
          }
          return updated;
        }
        return l;
      }),
    );
  };

  // Check for stock issues
  const hasStockIssues = lines.some(
    (l) =>
      l.article && l.availableQty !== undefined && l.quantity > l.availableQty,
  );

  const totalQuantity = lines.reduce((sum, l) => sum + (l.quantity || 0), 0);

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!warehouseId) {
      newErrors.warehouseId = "Seleziona un magazzino";
    }
    if (!movementDate) {
      newErrors.movementDate = "Inserisci la data";
    }
    const validLines = lines.filter((l) => l.article && l.quantity > 0);
    if (validLines.length === 0) {
      newErrors.lines = "Inserisci almeno una riga con articolo e quantità";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (andConfirm: boolean = false) => {
    if (!validate()) return;

    const data: CreateMovementDto = {
      warehouseId: warehouseId as number,
      movementDate: movementDate!.format("YYYY-MM-DD"),
      documentNumber: documentNumber || undefined,
      externalReference: externalReference || undefined,
      notes: notes || undefined,
      lines: lines
        .filter((l) => l.article && l.quantity > 0)
        .map((l) => ({
          articleId: l.article!.id,
          quantity: l.quantity,
          notes: l.notes,
        })),
    };

    try {
      const result = await createMutation.mutateAsync(data);
      if (andConfirm) {
        await confirmMutation.mutateAsync(result.id);
      }
      navigate(`/warehouse/movements/${result.id}`);
    } catch (error) {
      console.error("Errore salvataggio:", error);
    }
  };

  const isPending = createMutation.isPending || confirmMutation.isPending;

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="it">
      <Box>
        {/* Header */}
        <Box sx={{ mb: 3, display: "flex", alignItems: "center", gap: 2 }}>
          <IconButton onClick={() => navigate(-1)}>
            <ArrowBackIcon />
          </IconButton>
          <Box>
            <Typography variant="h5" fontWeight="bold">
              Nuovo Scarico
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Movimento di uscita merce da magazzino
            </Typography>
          </Box>
        </Box>

        {(createMutation.error || confirmMutation.error) && (
          <Alert severity="error" sx={{ mb: 3 }}>
            Errore:{" "}
            {((createMutation.error || confirmMutation.error) as Error).message}
          </Alert>
        )}

        {hasStockIssues && (
          <Alert severity="warning" sx={{ mb: 3 }} icon={<WarningIcon />}>
            Attenzione: alcune righe superano la disponibilità in magazzino
          </Alert>
        )}

        {/* Form Header */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" gutterBottom>
            Dati Movimento
          </Typography>
          <Grid container spacing={2}>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <DatePicker
                label="Data Movimento"
                value={movementDate}
                onChange={setMovementDate}
                slotProps={{
                  textField: {
                    fullWidth: true,
                    required: true,
                    error: !!errors.movementDate,
                    helperText: errors.movementDate,
                  },
                }}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <FormControl fullWidth required error={!!errors.warehouseId}>
                <InputLabel>Magazzino</InputLabel>
                <Select
                  value={warehouseId}
                  label="Magazzino"
                  onChange={(e) => setWarehouseId(e.target.value as number)}
                >
                  {warehouses?.map((w) => (
                    <MenuItem key={w.id} value={w.id}>
                      {w.name}
                      {w.isDefault && (
                        <Chip label="Default" size="small" sx={{ ml: 1 }} />
                      )}
                    </MenuItem>
                  ))}
                </Select>
                {errors.warehouseId && (
                  <Typography variant="caption" color="error">
                    {errors.warehouseId}
                  </Typography>
                )}
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <TextField
                fullWidth
                label="Numero Documento"
                value={documentNumber}
                onChange={(e) => setDocumentNumber(e.target.value)}
                placeholder="DDT, Bolla, etc."
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <TextField
                fullWidth
                label="Riferimento Esterno"
                value={externalReference}
                onChange={(e) => setExternalReference(e.target.value)}
                placeholder="Ordine, Cliente, etc."
              />
            </Grid>
            <Grid size={12}>
              <TextField
                fullWidth
                label="Note"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                multiline
                rows={2}
              />
            </Grid>
          </Grid>
        </Paper>

        {/* Lines */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              mb: 2,
            }}
          >
            <Typography variant="h6">Righe Movimento</Typography>
            <Button startIcon={<AddIcon />} onClick={handleAddLine}>
              Aggiungi Riga
            </Button>
          </Box>

          {errors.lines && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {errors.lines}
            </Alert>
          )}

          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ width: "40%" }}>Articolo</TableCell>
                  <TableCell sx={{ width: "15%" }} align="right">
                    Disponibile
                  </TableCell>
                  <TableCell sx={{ width: "15%" }} align="right">
                    Quantità
                  </TableCell>
                  <TableCell sx={{ width: "20%" }}>Note</TableCell>
                  <TableCell sx={{ width: 60 }}></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {lines.map((line) => {
                  const isOverStock =
                    line.article &&
                    line.availableQty !== undefined &&
                    line.quantity > line.availableQty;
                  return (
                    <TableRow
                      key={line.id}
                      sx={isOverStock ? { bgcolor: "warning.light" } : {}}
                    >
                      <TableCell>
                        <Autocomplete
                          value={line.article}
                          onChange={(_, value) =>
                            handleLineChange(line.id, "article", value)
                          }
                          options={articles || []}
                          getOptionLabel={(option) =>
                            `${option.code} - ${option.description}`
                          }
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              size="small"
                              placeholder="Seleziona articolo"
                            />
                          )}
                          isOptionEqualToValue={(option, value) =>
                            option.id === value.id
                          }
                        />
                      </TableCell>
                      <TableCell align="right">
                        {line.article ? (
                          <Chip
                            label={`${formatQuantity(line.availableQty || 0)} ${line.article.unitOfMeasure}`}
                            size="small"
                            color={
                              (line.availableQty || 0) <= 0
                                ? "error"
                                : "default"
                            }
                          />
                        ) : (
                          "-"
                        )}
                      </TableCell>
                      <TableCell>
                        <Box sx={{ display: "flex", alignItems: "center" }}>
                          <TextField
                            size="small"
                            type="number"
                            value={line.quantity}
                            onChange={(e) =>
                              handleLineChange(
                                line.id,
                                "quantity",
                                parseFloat(e.target.value) || 0,
                              )
                            }
                            slotProps={{
                              htmlInput: { min: 0, step: 0.01 },
                              input: {
                                endAdornment: line.article && (
                                  <InputAdornment position="end">
                                    {line.article.unitOfMeasure}
                                  </InputAdornment>
                                ),
                              },
                            }}
                            error={isOverStock ?? undefined}
                            fullWidth
                          />
                          {isOverStock && (
                            <Tooltip title="Quantità superiore alla disponibilità">
                              <WarningIcon
                                color="warning"
                                sx={{ fontSize: 16, ml: 1 }}
                              />
                            </Tooltip>
                          )}
                        </Box>
                      </TableCell>
                      <TableCell>
                        <TextField
                          size="small"
                          placeholder="Note"
                          value={line.notes || ""}
                          onChange={(e) =>
                            handleLineChange(line.id, "notes", e.target.value)
                          }
                          fullWidth
                        />
                      </TableCell>
                      <TableCell>
                        <IconButton
                          size="small"
                          onClick={() => handleRemoveLine(line.id)}
                          disabled={lines.length === 1}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>

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

          {/* Totals */}
          <Box sx={{ display: "flex", justifyContent: "flex-end" }}>
            <Box>
              <Typography variant="body2" color="text.secondary">
                Totale Quantità
              </Typography>
              <Typography variant="h6">{totalQuantity.toFixed(2)}</Typography>
            </Box>
          </Box>
        </Paper>

        {/* Actions */}
        <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
          <Button onClick={() => navigate(-1)}>Annulla</Button>
          <Button
            variant="outlined"
            startIcon={
              isPending ? <CircularProgress size={20} /> : <SaveIcon />
            }
            onClick={() => handleSubmit(false)}
            disabled={isPending}
          >
            Salva Bozza
          </Button>
          <Button
            variant="contained"
            startIcon={
              isPending ? <CircularProgress size={20} /> : <ConfirmIcon />
            }
            onClick={() => handleSubmit(true)}
            disabled={isPending || hasStockIssues}
            color="success"
          >
            Salva e Conferma
          </Button>
        </Box>
      </Box>
    </LocalizationProvider>
  );
}
