"use client";

import { useMemo } from "react";
import Link from "next/link";

import { Grid, Section } from "@/components/ui";
import { VideoGuide } from "@/entities/dashboard/types";
import { useVideoGuidePurchase } from "@/hooks/video-guides/useVideoGuidePurchase";

import { VideoGuideCard } from "../../cards";

import styles from "./VideoGuidesSection.module.scss";

interface VideoGuidesSectionProps {
  videoGuides: VideoGuide[];
}

function VideoGuideCardWrapper({ videoGuide }: { videoGuide: VideoGuide }) {
  const { handlePurchase, isCheckoutLoading, isProcessingPurchase } =
    useVideoGuidePurchase({
      videoGuideId: videoGuide.id,
      productId: videoGuide.productId, // Используем productId из payment-service
      productKey: videoGuide.key,
    });

  // Для купленных видео - ссылка на страницу просмотра
  const href = videoGuide.isPurchased
    ? `/video-guides/${videoGuide.id}`
    : "#";

  const isClickable = videoGuide.isPurchased;

  const cardElement = (
    <VideoGuideCard
      name={videoGuide.name}
      description={videoGuide.description}
      imageUrl={videoGuide.imageUrl}
      duration={videoGuide.duration}
      price={videoGuide.price}
      oldPrice={videoGuide.oldPrice}
      discount={videoGuide.discount}
      isPurchased={videoGuide.isPurchased}
      isCheckoutLoading={isCheckoutLoading}
      isProcessingPurchase={isProcessingPurchase}
      onPurchaseClick={!videoGuide.isPurchased ? handlePurchase : undefined}
    />
  );

  if (isClickable) {
    return (
      <Link href={href} key={`video-guide-${videoGuide.id}`}>
        {cardElement}
      </Link>
    );
  }

  return <div key={`video-guide-${videoGuide.id}`}>{cardElement}</div>;
}

export default function VideoGuidesSection({
  videoGuides,
}: VideoGuidesSectionProps) {
  // Сортируем видео: купленные в начало
  const sortedVideoGuides = useMemo(() => {
    if (!videoGuides || videoGuides.length === 0) {
      return [];
    }

    return [...videoGuides].sort((a, b) => {
      // Купленные видео идут первыми
      if (a.isPurchased && !b.isPurchased) return -1;
      if (!a.isPurchased && b.isPurchased) return 1;

      // Сохраняем исходный порядок для видео с одинаковым статусом покупки
      return 0;
    });
  }, [videoGuides]);

  if (sortedVideoGuides.length === 0) {
    return null;
  }

  const columns = sortedVideoGuides.length;

  return (
    <Section title="Video Guides" contentClassName={styles.sectionContent}>
      <Grid columns={columns} className={styles.grid}>
        {sortedVideoGuides.map(videoGuide => (
          <VideoGuideCardWrapper
            key={`video-guide-${videoGuide.id}`}
            videoGuide={videoGuide}
          />
        ))}
      </Grid>
    </Section>
  );
}
