import { 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,
  SwapHoriz as TransferIcon,
} 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,
  useStockLevels,
  useCreateTransferMovement,
  useConfirmMovement,
} from "../hooks";
import { ArticleDto, CreateTransferDto, formatQuantity } from "../types";

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

export default function TransferMovementPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [movementDate, setMovementDate] = useState<Dayjs | null>(dayjs());
  const [sourceWarehouseId, setSourceWarehouseId] = useState<number | "">("");
  const [destWarehouseId, setDestWarehouseId] = 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: sourceWarehouseId || undefined,
  });
  const createMutation = useCreateTransferMovement();
  const confirmMutation = useConfirmMovement();

  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 };
          if (field === "article" && value) {
            const article = value as ArticleDto;
            updated.availableQty = getAvailableQty(article.id);
          }
          return updated;
        }
        return l;
      }),
    );
  };

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

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!sourceWarehouseId) {
      newErrors.sourceWarehouseId = t("warehouse.transfer.validation.sourceRequired");
    }
    if (!destWarehouseId) {
      newErrors.destWarehouseId = t("warehouse.transfer.validation.destRequired");
    }
    if (
      sourceWarehouseId &&
      destWarehouseId &&
      sourceWarehouseId === destWarehouseId
    ) {
      newErrors.destWarehouseId =
        t("warehouse.transfer.validation.sameWarehouse");
    }
    if (!movementDate) {
      newErrors.movementDate = t("warehouse.transfer.validation.dateRequired");
    }
    const validLines = lines.filter((l) => l.article && l.quantity > 0);
    if (validLines.length === 0) {
      newErrors.lines = t("warehouse.transfer.validation.linesRequired");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    const data: CreateTransferDto = {
      sourceWarehouseId: sourceWarehouseId as number,
      destinationWarehouseId: destWarehouseId 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:", 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 sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <TransferIcon color="primary" />
            <Box>
              <Typography variant="h5" fontWeight="bold">
                {t("warehouse.transfer.title")}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {t("warehouse.transfer.subtitle")}
              </Typography>
            </Box>
          </Box>
        </Box>

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

        {/* Form */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" gutterBottom>
            {t("warehouse.transfer.sections.transferData")}
          </Typography>
          <Grid container spacing={2}>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <DatePicker
                label={t("warehouse.transfer.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.sourceWarehouseId}
              >
                <InputLabel>{t("warehouse.transfer.fields.sourceWarehouse")}</InputLabel>
                <Select
                  value={sourceWarehouseId}
                  label={t("warehouse.transfer.fields.sourceWarehouse")}
                  onChange={(e) =>
                    setSourceWarehouseId(e.target.value as number)
                  }
                >
                  {warehouses
                    ?.filter((w) => w.id !== destWarehouseId)
                    .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 required error={!!errors.destWarehouseId}>
                <InputLabel>{t("warehouse.transfer.fields.destWarehouse")}</InputLabel>
                <Select
                  value={destWarehouseId}
                  label={t("warehouse.transfer.fields.destWarehouse")}
                  onChange={(e) => setDestWarehouseId(e.target.value as number)}
                >
                  {warehouses
                    ?.filter((w) => w.id !== sourceWarehouseId)
                    .map((w) => (
                      <MenuItem key={w.id} value={w.id}>
                        {w.name}
                      </MenuItem>
                    ))}
                </Select>
                {errors.destWarehouseId && (
                  <Typography variant="caption" color="error">
                    {errors.destWarehouseId}
                  </Typography>
                )}
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, sm: 6, md: 3 }}>
              <TextField
                fullWidth
                label={t("warehouse.transfer.fields.document")}
                value={documentNumber}
                onChange={(e) => setDocumentNumber(e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label={t("warehouse.transfer.fields.externalReference")}
                value={externalReference}
                onChange={(e) => setExternalReference(e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label={t("warehouse.transfer.fields.notes")}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
              />
            </Grid>
          </Grid>
        </Paper>

        {/* Lines */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Box sx={{ display: "flex", justifyContent: "space-between", mb: 2 }}>
            <Typography variant="h6">{t("warehouse.transfer.sections.lines")}</Typography>
            <Button startIcon={<AddIcon />} onClick={handleAddLine}>
              {t("warehouse.transfer.actions.add")}
            </Button>
          </Box>

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

          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t("warehouse.transfer.fields.article")}</TableCell>
                  <TableCell align="right">{t("warehouse.transfer.fields.available")}</TableCell>
                  <TableCell align="right">{t("warehouse.transfer.fields.quantity")}</TableCell>
                  <TableCell>{t("warehouse.transfer.fields.notes")}</TableCell>
                  <TableCell width={60}></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {lines.map((line) => (
                  <TableRow key={line.id}>
                    <TableCell>
                      <Autocomplete
                        value={line.article}
                        onChange={(_, v) =>
                          handleLineChange(line.id, "article", v)
                        }
                        options={articles || []}
                        getOptionLabel={(o) => `${o.code} - ${o.description}`}
                        renderInput={(params) => (
                          <TextField
                            {...params}
                            size="small"
                            placeholder={t("warehouse.transfer.placeholders.article")}
                          />
                        )}
                        isOptionEqualToValue={(o, v) => o.id === v.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>
                      <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"
                        value={line.notes || ""}
                        onChange={(e) =>
                          handleLineChange(line.id, "notes", e.target.value)
                        }
                        placeholder={t("warehouse.transfer.placeholders.notes")}
                        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 }} />
          <Box sx={{ display: "flex", justifyContent: "flex-end" }}>
            <Typography variant="h6">
              {t("warehouse.transfer.totals.total", { value: formatQuantity(totalQuantity) })}
            </Typography>
          </Box>
        </Paper>

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