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,
} from "@mui/material";
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Add as AddIcon,
  Delete as DeleteIcon,
  Check as ConfirmIcon,
} from "@mui/icons-material";
import { useTranslation } from "react-i18next";
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,
  useCreateInboundMovement,
  useConfirmMovement,
} from "../hooks";
import { ArticleDto, CreateMovementDto, formatCurrency } from "../types";

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

export default function InboundMovementPage() {
  const { t } = useTranslation();
  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, unitCost: 0 },
  ]);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const { data: warehouses } = useWarehouses({ active: true });
  const { data: articles } = useArticles({ isActive: true });
  const createMutation = useCreateInboundMovement();
  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]);

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

  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 };
          // Auto-fill unit cost from article
          if (field === "article" && value) {
            const article = value as ArticleDto;
            updated.unitCost =
              article.lastPurchaseCost || article.weightedAverageCost || 0;
          }
          return updated;
        }
        return l;
      }),
    );
  };

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

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!warehouseId) {
      newErrors.warehouseId = t("warehouse.inbound.validation.warehouseRequired");
    }
    if (!movementDate) {
      newErrors.movementDate = t("warehouse.inbound.validation.dateRequired");
    }
    const validLines = lines.filter((l) => l.article && l.quantity > 0);
    if (validLines.length === 0) {
      newErrors.lines = t("warehouse.inbound.validation.linesRequired");
    }
    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,
          unitCost: l.unitCost,
          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">
              {t("warehouse.inbound.title")}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t("warehouse.inbound.subtitle")}
            </Typography>
          </Box>
        </Box>

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

        {/* Form Header */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" gutterBottom>
            {t("warehouse.inbound.sections.movementData")}
          </Typography>
          <Grid container spacing={2}>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <DatePicker
                label={t("warehouse.inbound.fields.date")}
                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>{t("warehouse.inbound.fields.warehouse")}</InputLabel>
                <Select
                  value={warehouseId}
                  label={t("warehouse.inbound.fields.warehouse")}
                  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={t("warehouse.inbound.fields.documentNumber")}
                value={documentNumber}
                onChange={(e) => setDocumentNumber(e.target.value)}
                placeholder={t("warehouse.inbound.placeholders.documentNumber")}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <TextField
                fullWidth
                label={t("warehouse.inbound.fields.externalReference")}
                value={externalReference}
                onChange={(e) => setExternalReference(e.target.value)}
                placeholder={t("warehouse.inbound.placeholders.externalReference")}
              />
            </Grid>
            <Grid size={12}>
              <TextField
                fullWidth
                label={t("warehouse.inbound.fields.notes")}
                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">{t("warehouse.inbound.sections.lines")}</Typography>
            <Button startIcon={<AddIcon />} onClick={handleAddLine}>
              {t("warehouse.inbound.actions.addLine")}
            </Button>
          </Box>

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

          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ width: "45%" }}>{t("warehouse.inbound.fields.article")}</TableCell>
                  <TableCell sx={{ width: "15%" }} align="right">
                    {t("warehouse.inbound.fields.quantity")}
                  </TableCell>
                  <TableCell sx={{ width: "15%" }} align="right">
                    {t("warehouse.inbound.fields.unitCost")}
                  </TableCell>
                  <TableCell sx={{ width: "15%" }} align="right">
                    {t("warehouse.inbound.fields.total")}
                  </TableCell>
                  <TableCell sx={{ width: 60 }}></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {lines.map((line) => (
                  <TableRow key={line.id}>
                    <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={t("warehouse.inbound.placeholders.selectArticle")}
                          />
                        )}
                        isOptionEqualToValue={(option, value) =>
                          option.id === value.id
                        }
                      />
                    </TableCell>
                    <TableCell>
                      <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>
                            ),
                          },
                        }}
                        fullWidth
                      />
                    </TableCell>
                    <TableCell>
                      <TextField
                        size="small"
                        type="number"
                        value={line.unitCost}
                        onChange={(e) =>
                          handleLineChange(
                            line.id,
                            "unitCost",
                            parseFloat(e.target.value) || 0,
                          )
                        }
                        slotProps={{
                          htmlInput: { min: 0, step: 0.01 },
                          input: {
                            startAdornment: (
                              <InputAdornment position="start">
                                €
                              </InputAdornment>
                            ),
                          },
                        }}
                        fullWidth
                      />
                    </TableCell>
                    <TableCell align="right">
                      <Typography fontWeight="medium">
                        {formatCurrency(line.quantity * line.unitCost)}
                      </Typography>
                    </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", gap: 4 }}>
            <Box>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.inbound.totals.quantity")}
              </Typography>
              <Typography variant="h6">{totalQuantity.toFixed(2)}</Typography>
            </Box>
            <Box>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.inbound.totals.value")}
              </Typography>
              <Typography variant="h6">{formatCurrency(totalValue)}</Typography>
            </Box>
          </Box>
        </Paper>

        {/* Actions */}
        <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
          <Button onClick={() => navigate(-1)}>{t("warehouse.inbound.actions.cancel")}</Button>
          <Button
            variant="outlined"
            startIcon={
              isPending ? <CircularProgress size={20} /> : <SaveIcon />
            }
            onClick={() => handleSubmit(false)}
            disabled={isPending}
          >
            {t("warehouse.inbound.actions.saveDraft")}
          </Button>
          <Button
            variant="contained"
            startIcon={
              isPending ? <CircularProgress size={20} /> : <ConfirmIcon />
            }
            onClick={() => handleSubmit(true)}
            disabled={isPending}
            color="success"
          >
            {t("warehouse.inbound.actions.saveAndConfirm")}
          </Button>
        </Box>
      </Box>
    </LocalizationProvider>
  );
}
