// components/remarks/RemarksViewer.tsx
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { GitBranch, MessageSquareText } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { ScrollArea } from "@/shared/common/ui/scroll-area";

import RemarkList from "./RemarkList";
import { useChildIncomingInstances } from "../components/hooks/useIncomingInstances";

interface RemarksViewerProps {
  incomingInstanceId: string;
}

type LocalizedText = {
  am?: string;
  en?: string;
};

type RemarkInstanceOptionSource = {
  assignee?: {
    employee?: {
      name?: LocalizedText;
    };
  } | null;
  assigneePosition?: {
    name?: LocalizedText;
  } | null;
};

const RemarksViewer: React.FC<RemarksViewerProps> = ({
  incomingInstanceId,
}) => {
  const { t, i18n } = useTranslation();
  const [selectedInstanceId, setSelectedInstanceId] =
    useState(incomingInstanceId);

  const { data: childInstancesData, isLoading: isLoadingInstances } =
    useChildIncomingInstances(incomingInstanceId, {
      enabled: !!incomingInstanceId,
  });
  const childInstances = childInstancesData ?? [];

  const getLocalizedText = (value?: LocalizedText | null) => {
    if (!value) return "";
    return i18n.language === "am"
      ? value.am || value.en || ""
      : value.en || value.am || "";
  };

  const getInstanceLabel = (
    instance: RemarkInstanceOptionSource,
    index: number,
  ) => {
    const assigneeName = getLocalizedText(instance.assignee?.employee?.name);
    const assigneePositionName = getLocalizedText(
      instance.assigneePosition?.name,
    );

    return (
      assigneeName ||
      assigneePositionName ||
      `${t("remark.childInstance", "Child Instance")} ${index + 1}`
    );
  };

  const instanceOptions = [
    {
      id: incomingInstanceId,
      label: t("remark.parentInstance", "Parent Instance"),
    },
    ...childInstances.map((instance, index) => ({
      id: instance.id,
      label: getInstanceLabel(instance, index),
    })),
  ];

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-lg">
          <MessageSquareText className="h-5 w-5" />
          {t("remark.remarksHistory", "Remarks History")}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Instance Selector */}
        <div className="space-y-2">
          <label className="text-sm font-medium">
            {t("remark.filterByInstance", "Filter by Instance")}
          </label>
          <Select
            value={selectedInstanceId}
            onValueChange={setSelectedInstanceId}
            disabled={isLoadingInstances}>
            <SelectTrigger>
              <SelectValue
                placeholder={t("remark.selectInstance", "Select instance")}
              />
            </SelectTrigger>
            <SelectContent>
              {instanceOptions.map((instance) => (
                <SelectItem key={instance.id} value={instance.id}>
                  <div className="flex items-center gap-2">
                    <GitBranch className="h-4 w-4" />
                    <span>{instance.label}</span>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Remarks List */}
        <ScrollArea className="h-[500px] pr-4">
          <RemarkList instanceIds={[selectedInstanceId]} />
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default RemarksViewer;
