import React, { useEffect } from "react";
import api from "./api";
import styled from "styled-components";
import moment from "moment";
import BoxIcon from "./boxIcon";
import InstructorMessage from "./messageSection";
import classNames from "classnames";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
import comingSoonIcon from "../../../assets/images/coming-soon-illustration.svg";
import CustomCarousel from "../components/carousel.jsx";

const DatabaseIcon = () => (
  <svg
    width="24"
    height="24"
    viewBox="0 0 24 24"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <ellipse cx="12" cy="5" rx="8" ry="3" stroke="#00C2C2" strokeWidth="1.5" />
    <path
      d="M20 12C20 13.6569 16.4183 15 12 15C7.58172 15 4 13.6569 4 12"
      stroke="#00C2C2"
      strokeWidth="1.5"
    />
    <path
      d="M20 5V19C20 20.6569 16.4183 22 12 22C7.58172 22 4 20.6569 4 19V5"
      stroke="#00C2C2"
      strokeWidth="1.5"
    />
  </svg>
);

const formatStorageSize = (bytes) => {
  if (!bytes && bytes !== 0) return "0.00";
  const gb = bytes / (1024 * 1024 * 1024);
  if (gb >= 1) return gb.toFixed(2);
  const mb = bytes / (1024 * 1024);
  return `${mb.toFixed(2)}MB`;
};

const AffiliateRightBar = ({
  planState,
  affiliateAccount,
  isPendingDelete,
}) => {
  const { findText } = useTranslation(wordStore);
  const {
    handleGetCoursesAffilateData,
    coursesAffilateData,
    storageSummaryData,
    handleGetStorageSummary,
  } = api();
  useEffect(() => {
    if (affiliateAccount) {
      handleGetCoursesAffilateData(
        {
          "status[]": "ending_soon,active,scheduled",
          page_size: 4,
        },
        affiliateAccount,
      );
      handleGetStorageSummary(affiliateAccount);
    }
  }, []);
  const courses = coursesAffilateData?.data?.results;
  const storageData = storageSummaryData?.data;
  const storageUsed = storageData?.total_size ?? 0;
  const storageTotal = storageData?.total_storage ?? 0;
  const storagePercent = storageData?.total_percentage?.toFixed(2) ?? 0;

  return (
    <EnterpriseContainer
      className={classNames({
        grace_period: planState === "GRACE PERIOD",
        pending_delete: isPendingDelete,
      })}
    >
      <Banner>
        <h3>{findText("Courses ending soon")}</h3>
        {courses?.length > 0 ? (
          <CustomCarousel
            items={courses}
            autoPlay
            interval={3500}
            renderItem={(course) => (
              <Course key={course?.id}>
                <img src={course?.thumbnail_dict?.url} alt="" />
                <div className="content">
                  <p className="date">
                    <span>{findText("Ends:")}</span>{" "}
                    {moment(course?.end_day).format("MMM DD, YYYY")}
                  </p>
                  <p className="name">{course?.name}</p>
                </div>
              </Course>
            )}
          />
        ) : (
          <EmptyCourse>
            <BoxIcon />
            <p>{findText("There is no course ending in the next 30 days")}</p>
          </EmptyCourse>
        )}
      </Banner>

      <ResourceCard>
        <div className="card-header">
          <div className="icon-wrapper">
            <DatabaseIcon />
          </div>
          <span className="card-title">{findText("Storage")}</span>
        </div>
        <div className="card-body">
          <div className="stats-row">
            <p className="usage">
              <span className="used">{formatStorageSize(storageUsed)}</span>
              <span className="total">
                {" "}
                / {formatStorageSize(storageTotal)}
                {storageTotal >= 1024 * 1024 * 1024 ? "GB" : ""}
              </span>
            </p>
            <p className="percent">
              {storagePercent}% {findText("used")}
            </p>
          </div>
          <ProgressTrack>
            <ProgressFill width={storagePercent} />
          </ProgressTrack>
        </div>
      </ResourceCard>

      <InstructorMessage
        title={findText("Coming soon")}
        titleColor="#FEBF10"
        bgColor="#fffaec"
        icon={comingSoonIcon}
        disabled={planState === "GRACE PERIOD"}
        isPendingDelete={isPendingDelete}
        messsage={findText(
          "Onboard and manage students with AI-powered instructor account",
        )}
        hideBtn
      />
    </EnterpriseContainer>
  );
};
const CustomDotsContainer = styled.li`
  border-radius: 3.091px;
  background: #dfe5e5;
  width: 8px;
  height: 4px;

  cursor: pointer;
  &.active {
    background-color: #00c2c2;
    width: 19px;
  }
`;
const Banner = styled.div`
  position: relative;
  padding: 0;
  border-radius: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
  text-align: left;

  h3 {
    font-size: 14px;
    font-weight: 600;
    letter-spacing: 0.28px;
    color: #313333;
  }
`;
const EnterpriseContainer = styled.div`
  background: #fff;
  max-width: 232px;
  width: 232px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  border-radius: 30.913px;
  border: 0.773px solid #dfe5e5;
  padding: 20px 18px;
  height: 638px;

  /* GRACE PERIOD AND DEACTIVATED */

  &.grace_period {
    border: 0.773px solid var(--Neutral-20, #dfe5e5);
    background: var(--Neutral-20, #dfe5e5);

    > div {
      border: 0.773px solid var(--Neutral-20, #dfe5e5);
      background: var(--Neutral-20, #dfe5e5);
    }
  }

  &.pending_delete {
    background-color: #dfe5e5;
  }

  .carousel-container {
    position: relative;

    .control-dots {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      align-items: center;
      gap: 10px;
      justify-content: center;
      bottom: 30;
    }
  }
`;
const ResourceCard = styled.div`
  background: #fff;
  border: 1px solid #f5f7f7;
  border-radius: 15px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;

  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .icon-wrapper {
    width: 40px;
    height: 38px;
    border-radius: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 6px 8px;
    background: #e5f9f9;
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #4a4d4d;
    flex: 1;
  }

  .card-body {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .stats-row {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 2px;
  }

  .usage {
    font-size: 14px;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0;
    .used {
      font-weight: 600;
      color: #7c8080;
    }
    .total {
      font-weight: 400;
      color: #adb2b2;
    }
  }

  .percent {
    font-size: 14px;
    font-weight: 400;
    color: #adb2b2;
    margin: 0;
    white-space: nowrap;
    flex-shrink: 0;
  }
`;
const ProgressTrack = styled.div`
  width: 100%;
  height: 10px;
  background: #f5f7f7;
  border-radius: 10px;
  overflow: hidden;
  margin-top: -12px;
`;
const ProgressFill = styled.div`
  height: 100%;
  width: ${(props) => Math.min(props.width || 0, 100)}%;
  background: #00c2c2;
  border-radius: 17px;
  transition: width 0.3s ease;
`;
const Course = styled.div`
  width: 100%;

  border-radius: 18.548px;
  overflow: hidden;
  position: relative;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0) 34.29%, #000 100%);

  > .content {
    position: relative;
    z-index: 2;
    flex: 1;
    height: 132px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    text-align: left;
    justify-content: space-between;
    > .date {
      border-radius: 6.183px;
      background: #fff;
      display: flex;
      gap: 4px;
      width: fit-content;
      align-items: center;
      height: 22.758px;
      padding: 3px 10px;
      color: #4a4d4d;
      text-align: center;
      font-size: 12px;
      span {
        color: #f95454;
      }
    }
    > .name {
      color: var(--white, #fff);
      font-size: 14px;
      font-weight: 700;
      width: 99%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  img {
    width: 100%;
    height: 100%;
    opacity: 0.4;
    position: absolute;
    inset: 0;
    object-fit: cover;
  }
`;
const EmptyCourse = styled.div`
  height: 132px;
  width: 100%;
  border-radius: 20px;
  background: #f5f7f7;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  > p {
    color: #636666;
    text-align: center;
    width: 100%;
    max-width: 144px;
    margin: 0 auto;
    font-size: 12px;
  }
`;
export default AffiliateRightBar;
