"use client";
import React, { useEffect, useRef, useState } from "react";

import noteListHandler from "./noteListHandler";
import SendNote from "./sendNote";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useSearchParams } from "next/navigation";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
// import style from "@/components/tanstack-table/style.module.scss";
import style from "./style.module.scss";
import {
  ArchiveRestore,
  CalendarCheckIcon,
  CalendarHeart,
  CalendarIcon,
  ClockIcon,
  Pencil,
  Plus,
} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import Axios from "@/lib/Axios";
import { PaginationStructT } from "@/types/global";
import { NotesT } from "@/types/notes";
import { format } from "date-fns";
import { getRandomDarkColor } from "@/lib/getRandomDarkColor";

const OrdersAndNotes = ({ id }: { id: number }) => {
  const { data, error, isLoading, isSuccess, refetch } = useQuery({
    queryKey: ["list-customer-comments1"],
    queryFn: fetchData,
  });

  // const { insertNode } = useCommentHandler();

  async function fetchData() {
    return Axios.get<PaginationStructT<NotesT[]>>("/customer/notes/", {
      params: {
        customer: id,
        ordering: "-created_at",
      },
    }).then((res) => {
      // for (let i of res.data.data) {
      //   insertNode(i, noteCommentStruct);
      // }

      return res.data.data;
    });
  }

  // const { ReturnNote, refetch } = noteListHandler(id);
  const searchParams = useSearchParams();
  const firstName = searchParams.get("firstName");
  const lastName = searchParams.get("lastName");

  return (
    <div className="space-y-3 pb-8">
      <div className="right-card h-96 bg-white border rounded-sm pt-5 space-y-10 px-8">
        <p className=" text-xl font-semibold">Order List</p>

        <div className="text-danger mt-2 gap-4">
          <Table className={`${style.table} ${style.scrollable}`}>
            <TableHeader className={` ${style.thead}`}>
              <TableRow className={`${style.tr}`}>
                <TableHead className={` ${style.th}`}>Date & Time</TableHead>
                <TableHead className={` ${style.th}`}>Agent</TableHead>
                <TableHead className={` ${style.th}`}>Order ID</TableHead>
                <TableHead className={` ${style.th}`}>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody className={`${style.tbody}`}>
              {/* <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>
                  <div className="space-y-3">
                    <p className="space-x-1">
                      <CalendarIcon className="inline w-4 h-4" />{" "}
                      <span>01 July, 2024</span>
                    </p>
                    <p className="space-x-1">
                      <ClockIcon className="inline w-4 h-4" />{" "}
                      <span>Monday, 10: 30PM</span>
                    </p>
                  </div>
                </TableCell>
                <TableCell className={`${style.td} `}>Megha</TableCell>
                <TableCell className={`${style.td} `}>Odi8</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>
                  <span>Dispatched </span>{" "}
                  <ArchiveRestore className="inline w-10 h-10" />
                </TableCell>
              </TableRow> */}
              {/* <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow>

              <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow>

              <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow>

              <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow>

              <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow>

              <TableRow className={`${style.tr}`}>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} `}>NA</TableCell>
                <TableCell className={`${style.td} space-x-1 `}>NA</TableCell>
              </TableRow> */}
            </TableBody>
          </Table>
          <p className="text-lg text-center mt-8">No Record</p>
        </div>
      </div>

      <div className="right-card bg-yellowish/20 rounded-sm py-5 space-y-10 px-8">
        <p className=" text-xl font-semibold">Notes</p>
        <div className="h-[20rem] py-2 overflow-hidden overflow-y-scroll ">
          <div className="text-danger flex items-start gap-4 mb-10">
            <Avatar>
              <AvatarImage alt="@shadcn" />
              <AvatarFallback className="bg-primary text-white">
                {firstName?.charAt(0).toUpperCase() +
                  "" +
                  lastName?.charAt(0).toUpperCase() +
                  ""}
              </AvatarFallback>
            </Avatar>

            <SendNote id={id} refetch={refetch} />
          </div>
          {/* <ListComments id={1} /> */}
          {/* <ReturnNote /> */}
          <DisplayNote data={data || []} customerId={id} refetch={refetch} />
        </div>
      </div>
    </div>
  );
};

function DisplayNote({
  data,
  refetch,
  customerId,
  viewAmemded = false,
}: {
  data: NotesT[];
  refetch: () => void;
  customerId: number;
  viewAmemded?: boolean;
}) {
  return (
    <div className="space-y-3 ">
      {data?.map((item) => {
        return (
          <CommentNote
            customerId={customerId}
            data={item}
            refetch={refetch}
            key={item.id}
            viewAmemded={viewAmemded}
          />
        );
      })}
    </div>
  );
}

function CommentNote({
  data,
  customerId,
  refetch,
  viewAmemded,
}: {
  data: NotesT;
  customerId: number;
  refetch: () => void;
  viewAmemded: boolean;
}) {
  const [open, setOpen] = useState(viewAmemded);

  function toggle() {
    setOpen((prev) => !prev);
  }

  return (
    <div key={data.id} className="text-black ">
      <div className="flex datas-start gap-4 w-full">
        <Avatar>
          <AvatarImage alt="@shadcn" />
          <AvatarFallback
            style={{
              backgroundColor: getRandomDarkColor(),
            }}
            className=" text-white"
          >
            {/* {(data.created_by_name || "").charAt(0)?.toUpperCase()} */}
          </AvatarFallback>
        </Avatar>

        <CommentBox
          customerId={customerId}
          refetch={refetch}
          toggle={toggle}
          data={data}
        />
      </div>
      {open && (
        <div className=" ml-16 mt-5">
          <DisplayNote
            customerId={customerId}
            refetch={refetch}
            data={data?.replies}
            viewAmemded={open}
          />
        </div>
      )}
    </div>
  );
}

function CommentBox({
  data,
  toggle,
  customerId,
  refetch,
}: {
  data: NotesT;
  toggle: () => void;
  customerId: number;
  refetch: () => void;
}) {
  const [commentToggle, setCommentToggle] = useState(false);

  return (
    <div className="bg-white rounded-lg p-2 w-full relative">
      <p className="">
        <span className="font-semibold">{data.created_by_name + " "}</span>

        {format(data?.updated_at, "dd MMM, yyyy ") +
          "at" +
          format(data?.updated_at, " h:mm aa")}{" "}
        {/* {data?.updated_at + ""} */}
      </p>
      <div className="">
        <ClampText key={data.id} text={data?.note} />
      </div>
      {data?.replies?.length > 0 && (
        <p
          className="cursor-pointer text-sm"
          onClick={() => data?.replies.length && toggle()}
        >
          amended ({data?.total_parents_count})
        </p>
      )}

      {data.child_note === null && commentToggle && (
        <div className="my-2">
          <SendNote id={customerId} parent_id={data.id} refetch={refetch} />
        </div>
      )}

      {data.child_note === null && (
        <Pencil
          className="w-5 absolute right-2 top-2 cursor-pointer"
          onClick={() => setCommentToggle((prev) => !prev)}
        />
      )}
    </div>
  );
}

const ClampText = ({ text }: { text: string }) => {
  const pRef = useRef<HTMLParagraphElement>(null);
  const [show, setShow] = useState(false);
  const [showBtn, setShowBtn] = useState(false);

  function countLines() {
    if (!pRef.current) return;
    const divHeight = pRef?.current?.offsetHeight;
    const lineHeight = parseInt(pRef?.current?.style.lineHeight);

    const lines = divHeight / lineHeight;
    return lines;
  }
  useEffect(() => {
    const lines = countLines() || 0;

    if (lines > 2) {
      setShowBtn(true);
    }
  }, []);

  return (
    <div>
      <div
        ref={pRef}
        className={`text-black ${
          !show && " line-clamp-3 "
        } whitespace-pre-wrap my-2`}
        style={{ lineHeight: "20px" }}
      >
        {text}
      </div>

      {showBtn && (
        <p
          onClick={(e) => {
            e.stopPropagation();
            setShow((prev) => !prev);
          }}
          className="text-danger cursor-pointer text-right text-sm"
        >
          {!show ? "View more" : "View less"}
        </p>
      )}
    </div>
  );
};

export default OrdersAndNotes;
