"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,
} 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(["printer", "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 || "",
    brand: printer.brand ?? "Canon",
    dpi: printer.dpi || undefined,
    description: printer.description || "",
  });

  useEffect(() => {
    if (formData.type !== "Label") {
      setFormData((prev) => ({ ...prev, dpi: undefined }));
    }
    if (formData.type === "A4") {
      if (!formData.brand) {
        setFormData((prev) => ({ ...prev, brand: "Canon" }));
      }
    } else if (formData.type === "Label") {
      setFormData((prev) => ({ ...prev, brand: "Zebra" }));
    } else {
      setFormData((prev) => ({ ...prev, brand: 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 handleBrandChange = useCallback((e: SelectChangeEvent) => {
    const value = e.target.value;
    setFormData((prev) => ({
      ...prev,
      brand: 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={t("IP")}
            value={formData.ip}
            onChange={handleChange("ip")}
            variant="outlined"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t("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>
        {formData.type === "A4" && (
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel>{t("Brand")}</InputLabel>
              <Select
                label={t("Brand")}
                value={formData.brand ?? "Canon"}
                onChange={handleBrandChange}
              >
                <MenuItem value="Canon">Canon</MenuItem>
                <MenuItem value="Brother">Brother</MenuItem>
              </Select>
            </FormControl>
          </Grid>
        )}
        {formData.type === "Label" && (
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label={t("Brand")}
              value={formData.brand ?? "Zebra"}
              disabled
            />
          </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} md={6}>
          <TextField
            fullWidth
            label={t("Description")}
            value={formData.description || ""}
            onChange={handleChange("description")}
            variant="outlined"
          />
        </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;
