"use client";
import React, { useState, useEffect } from "react";
import { Container } from "@/components/ui/container";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { TypographyH3 } from "@/components/ui/typography";
import { packageService } from "@/services/packageService";
import type { PackageDeal } from "@/types/package";
import Link from "next/link";
import Image from "next/image";

const PackageShowcase: React.FC = () => {
  const [packages, setPackages] = useState<PackageDeal[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPackages = async () => {
      try {
        const data = await packageService.getFeaturedPackages();
        setPackages(data.slice(0, 4));
      } catch (error) {
        console.error('Error fetching packages:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchPackages();
  }, []);

  if (loading) {
    return (
      <section className="py-10 px-4 md:px-6">
        <Container>
          <div className="flex flex-wrap gap-5 items-stretch justify-center">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="w-full sm:w-[610px] h-96 bg-gray-200 rounded-[21px] animate-pulse"></div>
            ))}
          </div>
        </Container>
      </section>
    );
  }

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

  return (
    <section className="py-10 px-4 md:px-6">
      <Container>
        <div className="flex flex-wrap gap-5 items-stretch justify-center">
          {packages.map((pkg) => {
            const mainImage = pkg.images?.[0] || pkg.products?.[0]?.images?.[0] || '/assets/placeholder.png';
            const savings = pkg.savings || 0;

            return (
              <Card 
                key={pkg.id}
                className="w-full sm:w-[610px] backdrop-blur-none shadow-none rounded-[21px] px-5 py-6 sm:pt-[53px] sm:pb-9" 
                style={{ background: "#F3F4F6" }}
              >
                <div className="flex h-full flex-col">
                  <TypographyH3 className="text-[36px] sm:text-[45px] leading-[46px] sm:leading-12 font-bold prompt text-black text-center tracking-[-0.9px]">
                    {pkg.name}
                  </TypographyH3>
                  
                  {pkg.discount_percentage > 0 && (
                    <p className="mt-2 text-center text-[23px] leading-[29px] font-semibold text-black tracking-[-0.46px]">
                      {pkg.discount_percentage}% OFF
                    </p>
                  )}
                  
                  {pkg.description && (
                    <p className="mt-2 text-center text-[16px] leading-[22px] font-medium text-gray-700">
                      {pkg.description.slice(0, 80)}
                    </p>
                  )}

                  <div className="mt-6 sm:mt-[38px] sm:mr-[69px] relative grid place-items-end">
                    <div className="relative h-[180px] sm:h-[267px] w-[260px] sm:w-[323px]">
                      <Image 
                        src={mainImage} 
                        alt={pkg.name} 
                        fill 
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = '/assets/placeholder.png';
                        }}
                      />
                    </div>
                    
                    <Link href={`/packages/${pkg.slug}`}>
                      <Button className="absolute left-0 sm:left-11 bottom-[33px] inline-flex rounded-full hover:bg-black/85 bg-black text-white py-4 px-6 lg:px-[37px] text-[16px] leading-[21px] font-medium">
                        تعال شوف
                        <Image src="/assets/icons/arrow-down.svg" alt='arrow' width={18} height={18} />
                      </Button>
                    </Link>

                    {/* Package Details Badge */}
                    <div className="absolute top-0 left-0 bg-orange-500 text-white px-3 py-1 rounded-full text-sm font-semibold">
                      {pkg.products?.length || 0} منتجات
                    </div>
                    
                    {savings > 0 && (
                      <div className="absolute top-8 left-0 bg-green-500 text-white px-3 py-1 rounded-full text-xs font-semibold">
                        وفر {savings.toLocaleString()} د.ع
                      </div>
                    )}
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      </Container>
    </section>
  );
};

export default PackageShowcase;
