"use client";

import { useMemo, useState } from "react";

import AddRoundedIcon from "@mui/icons-material/AddRounded";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import DeleteOutlineRoundedIcon from "@mui/icons-material/DeleteOutlineRounded";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import FlagOutlinedIcon from "@mui/icons-material/FlagOutlined";
import InsightsOutlinedIcon from "@mui/icons-material/InsightsOutlined";
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  IconButton,
  Paper,
  Tab,
  Tabs,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Tooltip,
  Typography,
} from "@mui/material";

import { useAppLanguage } from "@/components/providers/app-language-provider";

import {
  useCreateMasterDataItem,
  useDeleteMasterDataItem,
  useMasterDataCategories,
  useMasterDataIndicators,
  useMasterDataStatuses,
  useUpdateMasterDataItem,
} from "../hook/use-master-data";
import type {
  MasterDataFormValue,
  MasterDataTab,
} from "../types/master-data-types";
import { MasterDataDeleteDialog } from "./master-data-delete-dialog";
import { MasterDataDialog } from "./master-data-dialog";

type TableRowData = {
  id: number;
  name: string;
  description?: string | null;
  createdAt?: string | null;
  code?: string | null;
};

const copy = {
  en: {
    pageTitle: "Master Data",
    pageDescription:
      "Manage system master data including categories, indicators and statuses.",
    categories: "Categories",
    indicators: "Indicators",
    statuses: "Statuses",
    category: "Category",
    indicator: "Indicator",
    status: "Status",
    categoryHelp: "Manage all categories in the system.",
    indicatorHelp: "Manage all indicators in the system.",
    statusHelp: "Manage all statuses in the system.",
    add: "Add",
    number: "#",
    name: "Name",
    description: "Description",
    code: "Code",
    createdAt: "Created At",
    actions: "Actions",
    noData: "No data found.",
    loading: "Loading data...",
    edit: "Edit",
    delete: "Delete",
  },
  kh: {
    pageTitle: "ទិន្នន័យមូលដ្ឋាន",
    pageDescription:
      "គ្រប់គ្រងទិន្នន័យមូលដ្ឋានរបស់ប្រព័ន្ធ រួមមាន ប្រភេទ សូចនាករ និងស្ថានភាព។",
    categories: "ប្រភេទ",
    indicators: "សូចនាករ",
    statuses: "ស្ថានភាព",
    category: "ប្រភេទ",
    indicator: "សូចនាករ",
    status: "ស្ថានភាព",
    categoryHelp: "គ្រប់គ្រងប្រភេទទាំងអស់នៅក្នុងប្រព័ន្ធ។",
    indicatorHelp: "គ្រប់គ្រងសូចនាករទាំងអស់នៅក្នុងប្រព័ន្ធ។",
    statusHelp: "គ្រប់គ្រងស្ថានភាពទាំងអស់នៅក្នុងប្រព័ន្ធ។",
    add: "បន្ថែម",
    number: "ល.រ",
    name: "ឈ្មោះ",
    description: "ការពិពណ៌នា",
    code: "កូដ",
    createdAt: "កាលបរិច្ឆេទបង្កើត",
    actions: "សកម្មភាព",
    noData: "មិនមានទិន្នន័យ។",
    loading: "កំពុងទាញទិន្នន័យ...",
    edit: "កែប្រែ",
    delete: "លុប",
  },
} as const;

function formatDate(value?: string | null) {
  if (!value) return "—";

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date);
}

export function MasterDataScreen() {
  const { language } = useAppLanguage();
  const isKhmer = language === "kh";
  const text = isKhmer ? copy.kh : copy.en;

  const fontFamily = isKhmer
    ? '"Battambang", "Kantumruy Pro", sans-serif'
    : '"Inter", "Segoe UI", Arial, sans-serif';

  const [activeTab, setActiveTab] =
    useState<MasterDataTab>("categories");

  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] =
    useState<"create" | "edit">("create");
  const [editingRow, setEditingRow] =
    useState<TableRowData | null>(null);

  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deletingRow, setDeletingRow] =
    useState<TableRowData | null>(null);

  const categoriesQuery = useMasterDataCategories(
    activeTab === "categories",
  );

  const indicatorsQuery = useMasterDataIndicators(
    activeTab === "indicators",
  );

  const statusesQuery = useMasterDataStatuses(
    activeTab === "statuses",
  );

  const createMutation = useCreateMasterDataItem(activeTab);
  const updateMutation = useUpdateMasterDataItem(activeTab);
  const deleteMutation = useDeleteMasterDataItem(activeTab);

  const rows: TableRowData[] = useMemo(() => {
    if (activeTab === "categories") {
      return (categoriesQuery.data ?? []).map((item) => ({
        id: item.id,
        name: item.name,
        createdAt: item.createdAt,
      }));
    }

    if (activeTab === "indicators") {
      return (indicatorsQuery.data ?? []).map((item) => ({
        id: item.id,
        name: item.name,
        description: item.description,
        createdAt: item.createdAt,
      }));
    }

    return (statusesQuery.data ?? []).map((item) => ({
      id: item.id,
      name: item.name,
      code: item.code,
      description: item.description,
    }));
  }, [
    activeTab,
    categoriesQuery.data,
    indicatorsQuery.data,
    statusesQuery.data,
  ]);

  const currentQuery =
    activeTab === "categories"
      ? categoriesQuery
      : activeTab === "indicators"
        ? indicatorsQuery
        : statusesQuery;

  const pagedRows = useMemo(() => {
    const start = page * rowsPerPage;
    return rows.slice(start, start + rowsPerPage);
  }, [rows, page, rowsPerPage]);

  const tabItems = [
    {
      value: "categories" as const,
      label: text.categories,
      icon: <CategoryOutlinedIcon sx={{ fontSize: 16 }} />,
    },
    {
      value: "indicators" as const,
      label: text.indicators,
      icon: <InsightsOutlinedIcon sx={{ fontSize: 16 }} />,
    },
    {
      value: "statuses" as const,
      label: text.statuses,
      icon: <FlagOutlinedIcon sx={{ fontSize: 16 }} />,
    },
  ];

  const singularTitle =
    activeTab === "categories"
      ? text.category
      : activeTab === "indicators"
        ? text.indicator
        : text.status;

  const sectionTitle =
    activeTab === "categories"
      ? text.categories
      : activeTab === "indicators"
        ? text.indicators
        : text.statuses;

  const sectionHelp =
    activeTab === "categories"
      ? text.categoryHelp
      : activeTab === "indicators"
        ? text.indicatorHelp
        : text.statusHelp;

  const isSaving =
    createMutation.isPending || updateMutation.isPending;

  const errorMessage =
    currentQuery.error instanceof Error
      ? currentQuery.error.message
      : createMutation.error instanceof Error
        ? createMutation.error.message
        : updateMutation.error instanceof Error
          ? updateMutation.error.message
          : deleteMutation.error instanceof Error
            ? deleteMutation.error.message
            : null;

  const handleSave = async (value: MasterDataFormValue) => {
    if (dialogMode === "create") {
      await createMutation.mutateAsync(value);
    } else if (editingRow) {
      await updateMutation.mutateAsync({
        id: editingRow.id,
        value,
      });
    }

    setDialogOpen(false);
    setEditingRow(null);
  };

  const handleDelete = async () => {
    if (!deletingRow) return;

    await deleteMutation.mutateAsync(deletingRow.id);
    setDeleteOpen(false);
    setDeletingRow(null);
  };

  return (
    <Box
      sx={{
        width: "100%",
        px: { xs: 2, md: 3 },
        py: { xs: 2.5, md: 3.5 },
        fontFamily,
        "& .MuiTypography-root, & .MuiButton-root, & .MuiTab-root, & .MuiTableCell-root, & .MuiTablePagination-root":
          {
            fontFamily,
          },
      }}
    >
      <Box sx={{ width: "100%", maxWidth: 1500, mx: "auto" }}>
        <Box
          sx={{
            mb: 1.5,
            display: "flex",
            flexDirection: { xs: "column", sm: "row" },
            justifyContent: "space-between",
            gap: 2,
          }}
        >
          <Box>
            <Typography
              component="h1"
              sx={{
                fontSize: { xs: 28, md: 34 },
                fontWeight: 800,
              }}
            >
              {text.pageTitle}
            </Typography>

            <Typography
              color="text.secondary"
              sx={{ mt: 0.5, fontSize: 15 }}
            >
              {text.pageDescription}
            </Typography>
          </Box>

          <Button
            startIcon={<AddRoundedIcon />}
            variant="contained"
            disabled={activeTab === "statuses"}
            onClick={() => {
              setDialogMode("create");
              setEditingRow(null);
              setDialogOpen(true);
            }}
            sx={{
              alignSelf: { xs: "stretch", sm: "flex-start" },
              minHeight: 40,
              px: 2,
              borderRadius: 2,
              textTransform: "none",
              fontWeight: 700,
              boxShadow: "none",
            }}
          >
            {text.add} {singularTitle}
          </Button>
        </Box>

        <Paper
          elevation={0}
          sx={{
            overflow: "hidden",
            borderRadius: 2,
            border: "1px solid",
            borderColor: "divider",
            maxWidth: 680,
          }}
        >
          <Tabs
            value={activeTab}
            onChange={(_event, value: MasterDataTab) => {
              setActiveTab(value);
              setPage(0);
              setEditingRow(null);
              setDeletingRow(null);
            }}
            variant="fullWidth"
            sx={{
              minHeight: 42,
              "& .MuiTabs-indicator": { height: 2 },
              "& .MuiTab-root": {
                minHeight: 42,
                py: 0.5,
                px: 1.25,
                fontSize: 13,
                fontWeight: 600,
                textTransform: "none",
                gap: 0.5,
                borderRight: "1px solid",
                borderColor: "divider",
              },
              "& .MuiTab-root:last-of-type": {
                borderRight: "none",
              },
              "& .Mui-selected": {
                bgcolor: "action.selected",
              },
            }}
          >
            {tabItems.map((tab) => (
              <Tab
                key={tab.value}
                value={tab.value}
                icon={tab.icon}
                iconPosition="start"
                label={tab.label}
              />
            ))}
          </Tabs>
        </Paper>

        <Paper
          elevation={0}
          sx={{
            mt: 1.5,
            p: 2.5,
            borderRadius: 2.5,
            border: "1px solid",
            borderColor: "divider",
          }}
        >
          <Box sx={{ mb: 2 }}>
            <Typography sx={{ fontSize: 20, fontWeight: 750 }}>
              {sectionTitle}
            </Typography>

            <Typography
              color="text.secondary"
              sx={{ mt: 0.35, fontSize: 14 }}
            >
              {sectionHelp}
            </Typography>
          </Box>

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

          {currentQuery.isLoading ? (
            <Box
              sx={{
                py: 8,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 1.5,
              }}
            >
              <CircularProgress size={22} />
              <Typography color="text.secondary">
                {text.loading}
              </Typography>
            </Box>
          ) : (
            <>
              <TableContainer
                sx={{
                  border: "1px solid",
                  borderColor: "divider",
                  borderRadius: 2,
                }}
              >
                <Table sx={{ minWidth: 700 }}>
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ width: 70, fontWeight: 700 }}>
                        {text.number}
                      </TableCell>

                      <TableCell sx={{ fontWeight: 700 }}>
                        {singularTitle} {text.name}
                      </TableCell>

                      {activeTab === "categories" && (
                        <TableCell sx={{ width: 190, fontWeight: 700 }}>
                          {text.createdAt}
                        </TableCell>
                      )}

                      {activeTab === "indicators" && (
                        <>
                          <TableCell sx={{ fontWeight: 700 }}>
                            {text.description}
                          </TableCell>
                          <TableCell sx={{ width: 190, fontWeight: 700 }}>
                            {text.createdAt}
                          </TableCell>
                        </>
                      )}

                      {activeTab === "statuses" && (
                        <>
                          <TableCell sx={{ width: 160, fontWeight: 700 }}>
                            {text.code}
                          </TableCell>
                          <TableCell sx={{ fontWeight: 700 }}>
                            {text.description}
                          </TableCell>
                        </>
                      )}

                      <TableCell
                        align="center"
                        sx={{ width: 120, fontWeight: 700 }}
                      >
                        {text.actions}
                      </TableCell>
                    </TableRow>
                  </TableHead>

                  <TableBody>
                    {pagedRows.length === 0 ? (
                      <TableRow>
                        <TableCell
                          colSpan={
                            activeTab === "categories" ? 4 : 5
                          }
                          align="center"
                          sx={{ py: 7, color: "text.secondary" }}
                        >
                          {text.noData}
                        </TableCell>
                      </TableRow>
                    ) : (
                      pagedRows.map((row, index) => (
                        <TableRow hover key={row.id}>
                          <TableCell>
                            {page * rowsPerPage + index + 1}
                          </TableCell>

                          <TableCell sx={{ fontWeight: 600 }}>
                            {row.name}
                          </TableCell>

                          {activeTab === "categories" && (
                            <TableCell sx={{ color: "text.secondary" }}>
                              {formatDate(row.createdAt)}
                            </TableCell>
                          )}

                          {activeTab === "indicators" && (
                            <>
                              <TableCell sx={{ color: "text.secondary" }}>
                                {row.description || "—"}
                              </TableCell>

                              <TableCell sx={{ color: "text.secondary" }}>
                                {formatDate(row.createdAt)}
                              </TableCell>
                            </>
                          )}

                          {activeTab === "statuses" && (
                            <>
                              <TableCell>{row.code || "—"}</TableCell>
                              <TableCell>
                                {row.description || "—"}
                              </TableCell>
                            </>
                          )}

                          <TableCell align="center">
                            {activeTab !== "statuses" && (
                              <>
                                <Tooltip title={text.edit}>
                                  <IconButton
                                    size="small"
                                    color="primary"
                                    onClick={() => {
                                      setDialogMode("edit");
                                      setEditingRow(row);
                                      setDialogOpen(true);
                                    }}
                                    sx={{
                                      border: "1px solid",
                                      borderColor: "primary.main",
                                      borderRadius: 1.5,
                                      mr: 1,
                                    }}
                                  >
                                    <EditOutlinedIcon
                                      sx={{ fontSize: 18 }}
                                    />
                                  </IconButton>
                                </Tooltip>

                                <Tooltip title={text.delete}>
                                  <IconButton
                                    size="small"
                                    color="error"
                                    onClick={() => {
                                      setDeletingRow(row);
                                      setDeleteOpen(true);
                                    }}
                                    sx={{
                                      border: "1px solid",
                                      borderColor: "error.main",
                                      borderRadius: 1.5,
                                    }}
                                  >
                                    <DeleteOutlineRoundedIcon
                                      sx={{ fontSize: 18 }}
                                    />
                                  </IconButton>
                                </Tooltip>
                              </>
                            )}
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TableContainer>

              <TablePagination
                component="div"
                count={rows.length}
                page={page}
                onPageChange={(_event, value) => setPage(value)}
                rowsPerPage={rowsPerPage}
                onRowsPerPageChange={(event) => {
                  setRowsPerPage(Number(event.target.value));
                  setPage(0);
                }}
                rowsPerPageOptions={[5, 10, 25]}
              />
            </>
          )}
        </Paper>
      </Box>

      <MasterDataDialog
        open={dialogOpen}
        mode={dialogMode}
        tab={activeTab}
        initialValue={
          editingRow
            ? {
                name: editingRow.name,
                description: editingRow.description ?? "",
              }
            : null
        }
        loading={isSaving}
        language={isKhmer ? "kh" : "en"}
        fontFamily={fontFamily}
        onClose={() => setDialogOpen(false)}
        onSubmit={(value) => {
          void handleSave(value);
        }}
      />

      <MasterDataDeleteDialog
        open={deleteOpen}
        itemName={deletingRow?.name ?? ""}
        loading={deleteMutation.isPending}
        language={isKhmer ? "kh" : "en"}
        fontFamily={fontFamily}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => {
          void handleDelete();
        }}
      />
    </Box>
  );
}