"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  Button,
  Card,
  CardContent,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  Stack,
  Grid,
} from "@mui/material";
import { Check, Close } from "@mui/icons-material";
import axiosInstance from "@/app/(main)/axios/axiosInstance";
import { NEXT_PUBLIC_API_URL } from "@/config/api";

type Props = {
  id: number;
};

type EquipmentDetailData = {
  id: number;
  code: string;
  name: string;
  equipmentCode?: string;
  repairAndMaintenanceStatus?: boolean | null;
  repairAndMaintenanceRemarks?: string | null;
};

const UpdateMaintenanceForm: React.FC<Props> = ({ id }) => {
  const { t } = useTranslation(["equipment", "common"]);
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const [equipmentData, setEquipmentData] = useState<EquipmentDetailData | null>(null);
  const [status, setStatus] = useState<boolean | null>(null);
  const [remarks, setRemarks] = useState<string>("");

  useEffect(() => {
    const fetchEquipmentDetail = async () => {
      try {
        setFetching(true);
        const response = await axiosInstance.get<EquipmentDetailData>(
          `${NEXT_PUBLIC_API_URL}/EquipmentDetail/details/${id}`
        );
        if (response.data) {
          setEquipmentData(response.data);
          setStatus(response.data.repairAndMaintenanceStatus ?? null);
          setRemarks(response.data.repairAndMaintenanceRemarks ?? "");
        }
      } catch (error) {
        console.error("Error fetching equipment detail:", error);
      } finally {
        setFetching(false);
      }
    };

    fetchEquipmentDetail();
  }, [id]);

  const handleSave = useCallback(async () => {
    if (!equipmentData) return;

    try {
      setLoading(true);
      const updateData = {
        repairAndMaintenanceStatus: status,
        repairAndMaintenanceRemarks: remarks,
      };

      await axiosInstance.put(
        `${NEXT_PUBLIC_API_URL}/EquipmentDetail/update/${id}`,
        updateData,
        {
          headers: { "Content-Type": "application/json" },
        }
      );

      router.push("/settings/equipment?tab=1");
    } catch (error) {
      console.error("Error updating maintenance:", error);
      alert(t("Error saving data") || "Error saving data");
    } finally {
      setLoading(false);
    }
  }, [equipmentData, status, remarks, id, router, t]);

  const handleCancel = useCallback(() => {
    router.push("/settings/equipment?tab=1");
  }, [router]);

  if (fetching) {
    return (
      <Stack sx={{ p: 3 }}>
        <Typography>{t("Loading") || "Loading..."}</Typography>
      </Stack>
    );
  }

  if (!equipmentData) {
    return (
      <Stack sx={{ p: 3 }}>
        <Typography>{t("Equipment not found") || "Equipment not found"}</Typography>
      </Stack>
    );
  }

  return (
    <Stack
      spacing={2}
      component="form"
    >
      <Card>
        <CardContent component={Stack} spacing={4}>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Equipment Information")}
          </Typography>
          <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
            <Grid item xs={6}>
              <TextField
                label={t("Equipment Name") || "設備名稱"}
                value={equipmentData.code || ""}
                disabled
                fullWidth
                variant="filled"
                InputLabelProps={{
                  shrink: !!equipmentData.code,
                  sx: { fontSize: "0.9375rem" },
                }}
                InputProps={{
                  sx: { paddingTop: "8px" },
                }}
              />
            </Grid>

            <Grid item xs={6}>
              <TextField
                label={t("Equipment Code") || "設備編號"}
                value={equipmentData.equipmentCode || ""}
                disabled
                fullWidth
                variant="filled"
                InputLabelProps={{
                  shrink: !!equipmentData.equipmentCode,
                  sx: { fontSize: "0.9375rem" },
                }}
                InputProps={{
                  sx: { paddingTop: "8px" },
                }}
              />
            </Grid>

            <Grid item xs={6}>
              <FormControl fullWidth variant="filled">
                <InputLabel 
                  shrink={status !== null}
                  sx={{ fontSize: "0.9375rem" }}
                >
                  {t("Repair and Maintenance Status")}
                </InputLabel>
                <Select
                  value={status === null ? "" : status ? "yes" : "no"}
                  onChange={(e) => {
                    const value = e.target.value;
                    if (value === "yes") {
                      setStatus(true);
                    } else if (value === "no") {
                      setStatus(false);
                    } else {
                      setStatus(null);
                    }
                  }}
                  sx={{ paddingTop: "8px" }}
                >
                  <MenuItem value="yes">{t("Yes")}</MenuItem>
                  <MenuItem value="no">{t("No")}</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={6}>
              <TextField
                label={t("Repair and Maintenance Remarks")}
                value={remarks}
                onChange={(e) => setRemarks(e.target.value)}
                fullWidth
                multiline
                rows={4}
                variant="filled"
                InputLabelProps={{
                  shrink: true,
                  sx: { fontSize: "0.9375rem" },
                }}
                InputProps={{
                  sx: { 
                    paddingTop: "8px",
                    alignItems: "flex-start",
                    paddingBottom: "8px",
                  },
                }}
                sx={{
                  "& .MuiInputBase-input": {
                    paddingTop: "16px",
                  },
                }}
              />
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      <Stack direction="row" justifyContent="flex-end" gap={1}>
        <Button
          variant="outlined"
          startIcon={<Close />}
          onClick={handleCancel}
          disabled={loading}
          type="button"
        >
          {t("Cancel") || "取消"}
        </Button>
        <Button
          variant="contained"
          startIcon={<Check />}
          onClick={handleSave}
          disabled={loading}
          type="button"
        >
          {t("Save") || "保存"}
        </Button>
      </Stack>
    </Stack>
  );
};

export default UpdateMaintenanceForm;