import { Table, CampaignStatus, Tag } from "@komi-app/components";
import "../CampaignsTable.scss";
import moment from "moment";
import {
  CampaignType,
  CampaignItem,
  CampaignStatus as OmnichannelCampaignStatus,
  PaginatedItem,
} from "@komi-app/messaging-sdk";
import LegacyCampaignMenu from "../CampaignMenu";
import CampaignMenu from "./Menu/CampaignMenu";
import When from "@komi-app/when";
import { useEffect, useState } from "react";
import { getPhoneNumberService } from "services";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

interface SegmentItem {
  id: string;
  name: string;
}
export interface CampaignsTableProps {
  searchTerm: string;
  data: PaginatedItem<CampaignItem[]>;
  currentPageIndex?: number;
  pageCount?: number;
  onPageIndexChange?: (index: number) => any;
  loading: boolean;
  refetchTableData: () => void;
  disableSorting?: boolean;
  segmentsByTalent: SegmentItem[];
}

function formatPercent(value: number): string {
  return value.toLocaleString(undefined, { maximumFractionDigits: 2 }) + "%";
}

const OmniChannelTable = ({
  searchTerm,
  data,
  currentPageIndex,
  pageCount,
  onPageIndexChange,
  loading,
  refetchTableData,
  disableSorting = false,
  segmentsByTalent,
}: CampaignsTableProps) => {
  const [assignedNumber, setAssignedNumber] = useState<string>("");

  const isSmartScheduleCampaignEnabled = useFeatureIsOn(
    FLAGS.SMART_SCHEDULE_TALENT,
  );

  const filteredData = isSmartScheduleCampaignEnabled
    ? data
    : data.filter((row) => row.type !== CampaignType.SMART_SCHEDULE_EMAIL);

  useEffect(() => {
    async function getPhoneNumbers() {
      const phoneNumbers = await getPhoneNumberService().getAssignedNumbers();
      if (phoneNumbers.length) setAssignedNumber(phoneNumbers[0].phoneNumber);
    }
    getPhoneNumbers();
  }, []);

  return (
    <div className="campaigns-table">
      {/* TODO: CAMPAIGN_REMODEL: remove this type */}
      <Table<CampaignItem>
        loading={loading}
        noResultsRender={`No result matching “${searchTerm}”`}
        columns={
          filteredData.length
            ? [
                {
                  id: "Name",
                  header: "Name",
                  accessor: "name",
                },
                {
                  id: "Status",
                  header: "Status",
                  accessor: "status",
                  cell: ({ rowValue }) => (
                    <div
                      className="campaign-status-cell"
                      data-testid="status-cell"
                    >
                      <CampaignStatus
                        status={rowValue.status as OmnichannelCampaignStatus}
                      />
                    </div>
                  ),
                },
                {
                  id: "Segment",
                  header: "Segment",
                  accessor: ({ segmentIds }) => {
                    const segmentNames: string[] = [];
                    segmentIds?.forEach((segmentId: string) => {
                      const segment = segmentsByTalent.find(
                        (segment) => segment.id === segmentId,
                      );
                      segmentNames.push(segment?.name || "");
                    });

                    return segmentNames.join(", ");
                  },
                },
                {
                  id: "Open rate",
                  header: "Open rate",
                  accessor: "openRate",
                  cell: ({ rowValue }) => {
                    if (rowValue.type === CampaignType.SMS) return <>n/a</>;
                    if (rowValue.type === CampaignType.SMART_SCHEDULE_EMAIL) {
                      const openRate = rowValue.openRate;

                      if (typeof openRate === "number") {
                        return formatPercent(openRate);
                      }
                    } else if (
                      rowValue.type === CampaignType.EMAIL &&
                      typeof rowValue.openRate === "number"
                    ) {
                      formatPercent(rowValue.openRate);
                    }

                    return <>&ndash;</>;
                  },
                },
                {
                  id: "Click-through rate",
                  header: "Click-through rate",
                  accessor: "clickRate",
                  cell: ({ rowValue }) => {
                    if (
                      rowValue.type === CampaignType.EMAIL &&
                      typeof rowValue.clickRate === "number"
                    ) {
                      formatPercent(rowValue.clickRate);
                    } else if (
                      rowValue.type === CampaignType.SMART_SCHEDULE_EMAIL
                    ) {
                      const clickRate = rowValue.clickRate;

                      if (typeof clickRate === "number") {
                        return formatPercent(clickRate);
                      }
                    }

                    return <>&ndash;</>;
                  },
                },
                {
                  id: "Type",
                  header: "Type",
                  accessor: "type",
                  maxWidth: 92,
                  cell: ({ rowValue }) =>
                    rowValue.type === CampaignType.SMS ? (
                      <Tag text="SMS" colour="green" />
                    ) : (
                      <Tag text="EMAIL" colour="blue" />
                    ),
                },
                {
                  id: "Scheduled",
                  header: "Scheduled",
                  accessor: "scheduledTimestamp",
                  cell: ({ rowValue }) =>
                    rowValue.scheduledTimestamp ? (
                      moment(new Date(rowValue.scheduledTimestamp)).format(
                        "ddd DD MMM, YYYY",
                      )
                    ) : (
                      <>&ndash;</>
                    ),
                },
                {
                  id: "Menu",
                  header: "",
                  maxWidth: 50,
                  cell: ({ rowValue }) => (
                    // TODO: CAMPAIGN_REMODEL: Normalize to one element
                    <When
                      value={rowValue.type}
                      then={{
                        [CampaignType.SMS]: (
                          <CampaignMenu
                            assignedNumber={assignedNumber}
                            campaign={rowValue}
                            refetchTableData={refetchTableData}
                          />
                        ),
                        [CampaignType.SMART_SCHEDULE_EMAIL]: (
                          <CampaignMenu
                            assignedNumber={assignedNumber}
                            campaign={rowValue}
                            refetchTableData={refetchTableData}
                          />
                        ),
                        [CampaignType.EMAIL]: (
                          <LegacyCampaignMenu
                            campaignId={rowValue.id}
                            campaignName={rowValue.name || ""}
                            campaignStatus={
                              rowValue.status as OmnichannelCampaignStatus
                            }
                            refetchTableData={refetchTableData}
                            campaignScheduledTime={
                              rowValue.scheduledTimestamp || 0
                            }
                          />
                        ),
                      }}
                    />
                  ),
                },
              ]
            : []
        }
        inputData={filteredData}
        currentPageIndex={currentPageIndex}
        pageCount={pageCount}
        searchTerm={searchTerm}
        isSortingEnabled={!disableSorting}
        hasExternalPagination={pageCount === undefined ? false : true}
        onPageChangeCallback={onPageIndexChange}
      />
    </div>
  );
};

export default OmniChannelTable;
