"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { PrinterResult } from "@/app/api/settings/printer";
import { editPrinter, PrinterInputs } from "@/app/api/settings/printer/actions";
import {
  Box,
  Button,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import { Check, ArrowBack } from "@mui/icons-material";
import { successDialog } from "../Swal/CustomAlerts";

type Props = {
  printer: PrinterResult;
};

const EditPrinter: React.FC<Props> = ({ printer }) => {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState<PrinterInputs>({
    name: printer.name || "",
    ip: printer.ip || "",
    port: printer.port || undefined,
    type: printer.type || "",
    dpi: printer.dpi || undefined,
  });

  useEffect(() => {
    if (formData.type !== "Label") {
      setFormData((prev) => ({ ...prev, dpi: undefined }));
    }
  }, [formData.type]);

  const handleChange = useCallback((field: keyof PrinterInputs) => {
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      setFormData((prev) => ({
        ...prev,
        [field]: field === "port" || field === "dpi" 
          ? (value === "" ? undefined : parseInt(value, 10))
          : value,
      }));
    };
  }, []);

  const handleTypeChange = useCallback((e: SelectChangeEvent) => {
    const value = e.target.value;
    setFormData((prev) => ({
      ...prev,
      type: value,
    }));
  }, []);

  const handleSubmit = useCallback(async () => {
    setIsSubmitting(true);
    try {
      await editPrinter(printer.id, formData);
      successDialog(t("Save") || "儲存成功", t);
      router.push("/settings/printer");
      router.refresh();
    } catch (error) {
      console.error("Failed to update printer:", error);
      const errorMessage = error instanceof Error ? error.message : (t("Error saving data") || "儲存失敗");
      alert(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, printer.id, router, t]);

  return (
    <Box sx={{ mt: 3 }}>
      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t("Name")}
            value={formData.name}
            onChange={handleChange("name")}
            variant="outlined"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label="IP"
            value={formData.ip}
            onChange={handleChange("ip")}
            variant="outlined"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label="Port"
            type="number"
            value={formData.port || ""}
            onChange={handleChange("port")}
            variant="outlined"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <FormControl fullWidth>
            <InputLabel>{t("Type")}</InputLabel>
            <Select
              label={t("Type")}
              value={formData.type ?? ""}
              onChange={handleTypeChange}
            >
              <MenuItem value={"A4"}>A4</MenuItem>
              <MenuItem value={"Label"}>Label</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label="DPI"
            type="number"
            value={formData.dpi || ""}
            onChange={handleChange("dpi")}
            variant="outlined"
            disabled={formData.type !== "Label"}
          />
        </Grid>
        <Grid item xs={12}>
          <Stack direction="row" spacing={2}>
            <Button
              variant="outlined"
              startIcon={<ArrowBack />}
              onClick={() => router.push("/settings/printer")}
            >
              {t("Back")}
            </Button>
            <Button
              variant="contained"
              startIcon={<Check />}
              onClick={handleSubmit}
              disabled={isSubmitting}
            >
              {t("Save")}
            </Button>
          </Stack>
        </Grid>
      </Grid>
    </Box>
  );
};

export default EditPrinter;
