import { useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/common/ui/dialog";
import { useTranslation } from "react-i18next";
import { useRecordTags } from "@/user-management/hooks/useRecordTags";
import { RecordTagColumnDefn } from "./RecordTagsColumn";
import { RecordTagForm } from "./RecordTagForm";

export default function RecordTagsManagement({ unitId }: { unitId: string }) {
  const [pageIndex, setPageIndex] = useState(0);
  const [isOpen, setIsOpen] = useState(false);

  const { t } = useTranslation();

  // --- Record Tags Query ---
  const { recordTagsList, isLoadingRecordTagsList, refetchRecordTagsList } =
    useRecordTags({
      unitId: unitId ?? "",
    });

  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  if (isLoadingRecordTagsList) {
    return <div>{t("loading")}</div>;
  }

  return (
    <div className="p-6 space-y-6">
      <Card className="col-span-2 shadow-none border-none bg-transparent px-0">
        <CardHeader className="flex flex-row justify-between items-center px-0">
          <CardTitle className="text-xl font-semibold">
            {t("recordTag.title")}
          </CardTitle>

          {/* Create Button (opens modal) */}
          <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger asChild>
              <Button>{t("recordTag.createNew")}</Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t("recordTag.createTitle")}</DialogTitle>
              </DialogHeader>

              <RecordTagForm
                unitId={unitId}
                mode="create"
                onSuccess={() => {
                  setIsOpen(false);
                  refetchRecordTagsList();
                }}
              />
            </DialogContent>
          </Dialog>
        </CardHeader>

        {/* Record Tags Table */}
        <CardContent className="px-0">
          <AdvancedTable
            columns={RecordTagColumnDefn(unitId)}
            data={recordTagsList?.items || []}
            tableName={t("recordTag.tableName")}
            toolBarPosition="right"
            itemCount={recordTagsList?.count || 0}
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={() => handlePageChange(pageIndex + 1)}
            prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
          />
        </CardContent>
      </Card>
    </div>
  );
}
