"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import EditNote from "@mui/icons-material/EditNote";
import { fetchQcItemsForAll } from "@/app/api/settings/qcItemAll/actions";
import { QcItemResult } from "@/app/api/settings/qcItemAll";
import {
  deleteDialog,
  errorDialogWithContent,
  submitDialog,
  successDialog,
} from "../Swal/CustomAlerts";
import {
  deleteQcItemWithValidation,
  canDeleteQcItem,
  saveQcItemWithValidation,
  SaveQcItemInputs,
} from "@/app/api/settings/qcItemAll/actions";
import Delete from "@mui/icons-material/Delete";
import { Add } from "@mui/icons-material";
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack } from "@mui/material";
import QcItemDetails from "../QcItemSave/QcItemDetails";
import { FormProvider, useForm } from "react-hook-form";
import { translateQcItemAllBackendMessage } from "./qcItemAllMessages";

type SearchQuery = Partial<Omit<QcItemResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const Tab3QcItemManagement: React.FC = () => {
  const { t } = useTranslation("qcItemAll");
  const [qcItems, setQcItems] = useState<QcItemResult[]>([]);
  const [filteredQcItems, setFilteredQcItems] = useState<QcItemResult[]>([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingItem, setEditingItem] = useState<QcItemResult | null>(null);

  useEffect(() => {
    loadItems();
  }, []);

  const loadItems = async () => {
    const items = await fetchQcItemsForAll();
    setQcItems(items);
    setFilteredQcItems(items);
  };

  const formProps = useForm<SaveQcItemInputs>({
    defaultValues: {
      code: "",
      name: "",
      description: "",
    },
  });

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Name"), paramName: "name", type: "text" },
    ],
    [t]
  );

  const onReset = useCallback(() => {
    setFilteredQcItems(qcItems);
  }, [qcItems]);

  const handleEdit = useCallback((qcItem: QcItemResult) => {
    setEditingItem(qcItem);
    formProps.reset({
      id: qcItem.id,
      code: qcItem.code,
      name: qcItem.name,
      description: qcItem.description || "",
    });
    setOpenDialog(true);
  }, [formProps]);

  const handleAdd = useCallback(() => {
    setEditingItem(null);
    formProps.reset({
      code: "",
      name: "",
      description: "",
    });
    setOpenDialog(true);
  }, [formProps]);

  const handleSubmit = useCallback(async (data: SaveQcItemInputs) => {
    await submitDialog(async () => {
      try {
        const response = await saveQcItemWithValidation(data);
        if (response.errors) {
          let errorContents = "";
          for (const [key, value] of Object.entries(response.errors)) {
            formProps.setError(key as keyof SaveQcItemInputs, {
              type: "custom",
              message: translateQcItemAllBackendMessage(String(value), t),
            });
            errorContents =
              errorContents +
              translateQcItemAllBackendMessage(String(value), t) +
              "<br>";
          }
          errorDialogWithContent(t("Submit Error"), errorContents, t);
        } else {
          await successDialog(t("Submit Success"), t);
          setOpenDialog(false);
          await loadItems();
        }
      } catch (error) {
        const raw = error instanceof Error ? error.message : String(error);
        errorDialogWithContent(
          t("Submit Error"),
          translateQcItemAllBackendMessage(raw, t),
          t,
        );
      }
    }, t);
  }, [formProps, t]);

  const handleDelete = useCallback(async (qcItem: QcItemResult) => {
    // Check if can delete first
    const canDelete = await canDeleteQcItem(qcItem.id);
    
    if (!canDelete) {
      errorDialogWithContent(
        t("Cannot Delete"),
        t("Cannot delete QcItem. It is linked to one or more QcCategories."),
        t
      );
      return;
    }

    deleteDialog(async () => {
      try {
        const response = await deleteQcItemWithValidation(qcItem.id);
        if (!response.success || !response.canDelete) {
          errorDialogWithContent(
            t("Delete Error"),
            translateQcItemAllBackendMessage(
              response.message || t("Cannot Delete"),
              t,
            ),
            t,
          );
        } else {
          await successDialog(t("Delete Success"), t);
          await loadItems();
        }
      } catch (error) {
        const raw = error instanceof Error ? error.message : String(error);
        errorDialogWithContent(
          t("Delete Error"),
          translateQcItemAllBackendMessage(raw, t),
          t,
        );
      }
    }, t);
  }, [t]);

  const columnWidthSx = (width = "10%") => {
    return { width: width, whiteSpace: "nowrap" };
  };

  const columns = useMemo<Column<QcItemResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: handleEdit,
        buttonIcon: <EditNote />,
        sx: columnWidthSx("150px"),
      },
      { name: "code", label: t("Code"), sx: columnWidthSx() },
      { name: "name", label: t("Name"), sx: columnWidthSx() },
      { name: "description", label: t("Description") },
      {
        name: "id",
        label: t("Delete"),
        onClick: handleDelete,
        buttonIcon: <Delete />,
        buttonColor: "error",
      },
    ],
    [t, handleEdit, handleDelete]
  );

  return (
    <>
      <Stack direction="row" justifyContent="flex-end" sx={{ mb: 2 }}>
        <Button
          variant="contained"
          startIcon={<Add />}
          onClick={handleAdd}
        >
          {t("Create Qc Item")}
        </Button>
      </Stack>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredQcItems(
            qcItems.filter(
              (qi) =>
                (!query.code || qi.code.toLowerCase().includes(query.code.toLowerCase())) &&
                (!query.name || qi.name.toLowerCase().includes(query.name.toLowerCase()))
            )
          );
        }}
        onReset={onReset}
      />
      <SearchResults<QcItemResult>
        items={filteredQcItems}
        columns={columns}
      />

      {/* Add/Edit Dialog */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth sx={{ zIndex: 1000 }}>
        <DialogTitle>
          {editingItem ? t("Edit Qc Item") : t("Create Qc Item")}
        </DialogTitle>
        <FormProvider {...formProps}>
          <form onSubmit={formProps.handleSubmit(handleSubmit)}>
            <DialogContent>
              <QcItemDetails />
            </DialogContent>
            <DialogActions>
              <Button onClick={() => setOpenDialog(false)}>{t("Cancel")}</Button>
              <Button type="submit" variant="contained">
                {t("Submit")}
              </Button>
            </DialogActions>
          </form>
        </FormProvider>
      </Dialog>
    </>
  );
};

export default Tab3QcItemManagement;

