'use client';

/**
 * Service Card Component (Luxury E-commerce & Conversion Psychology)
 * 
 * Features:
 * - High quality image banner (h-48 w-full object-cover rounded-t-2xl)
 * - Glassmorphism heart button (bg-white/70 backdrop-blur-md) with retention state
 * - Top-left tags: Max 2 tags (Discount always on left/first, followed by Featured badge)
 * - Clean visual hierarchy without redundant category tag overlay
 * - Live data mapping (description, rating, review count)
 * - Conversion pricing with strikethrough original prices
 */

import React, { useState } from 'react';
import Link from 'next/link';
import { Card } from '../primitives/card';
import { ImageWithFallback } from '../primitives/image-with-fallback';
import { Star, Heart, CalendarCheck, Clock } from 'lucide-react';
import type { Service } from '@shinecode/api-client/types';

export interface ServiceCardProps {
  service: Service;
  locale?: string;
  isFavorite?: boolean;
  onToggleFavorite?: (service: Service) => void;
  onQuickBook?: (service: Service) => void;
}

export function ServiceCard({
  service,
  locale = 'en',
  isFavorite: initialIsFav = false,
  onToggleFavorite,
  onQuickBook,
}: ServiceCardProps) {
  const isAr = locale === 'ar';
  const [isFav, setIsFav] = useState(initialIsFav);

  const firstAttachment = service.attchments?.[0];
  const imageUrl =
    typeof firstAttachment === 'string'
      ? firstAttachment
      : firstAttachment?.url ||
        service.provider_image ||
        'https://images.unsplash.com/photo-1632345031435-8727f6897d53?w=800&h=600&fit=crop';

  let displayPrice = service.price;
  let discountPercent = 0;
  let hasDiscount = false;

  if (service.discount_price !== undefined && service.discount_price !== null && service.discount_price < service.price) {
    displayPrice = Math.round(service.discount_price);
    discountPercent = Math.round(((service.price - displayPrice) / service.price) * 100);
    hasDiscount = discountPercent > 0;
  } else if (service.discount !== undefined && service.discount !== null && service.discount > 0) {
    const discNum = Number(service.discount);
    if (discNum < 100) {
      discountPercent = Math.round(discNum);
      displayPrice = Math.round(service.price * (1 - discNum / 100));
      hasDiscount = true;
    } else if (discNum < service.price) {
      displayPrice = service.price - discNum;
      discountPercent = Math.round((discNum / service.price) * 100);
      hasDiscount = true;
    }
  }

  const isFeatured = Boolean(service.is_featured);
  const rawRating = Number(service.total_rating ?? service.rating ?? 0);
  const rating = rawRating > 0 ? rawRating : 5.0;
  const reviewCount = Number(service.total_review ?? service.review_count ?? 0);

  const handleHeartClick = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsFav(!isFav);
    onToggleFavorite?.(service);
  };

  const handleQuickBookClick = (e: React.MouseEvent) => {
    if (onQuickBook) {
      e.preventDefault();
      e.stopPropagation();
      onQuickBook(service);
    }
  };

  const formattedDuration = (() => {
    if (!service.duration) return '';
    const formatFromMinutes = (totalMinutes: number): string => {
      if (totalMinutes <= 0) return '';
      if (totalMinutes > 180) {
        const hours = Math.floor(totalMinutes / 60);
        const remMinutes = totalMinutes % 60;
        if (remMinutes === 0) {
          return isAr ? `${hours} ${hours >= 3 && hours <= 10 ? 'ساعات' : 'ساعة'}` : (hours === 1 ? '1 hr' : `${hours} hrs`);
        }
        return isAr ? `${hours} س و ${remMinutes} د` : `${hours}h ${remMinutes}m`;
      }
      return isAr ? `${totalMinutes} دقيقة` : `${totalMinutes} mins`;
    };

    if (typeof service.duration === 'number') {
      return formatFromMinutes(service.duration);
    }
    const str = String(service.duration).trim();
    if (!str) return '';
    if (str.includes(':')) {
      const parts = str.split(':');
      const h = parseInt(parts[0] ?? '0', 10) || 0;
      const m = parseInt(parts[1] ?? '0', 10) || 0;
      return formatFromMinutes(h * 60 + m);
    }
    const hMatch = str.match(/(\d+)\s*(?:h|hr|hours?)/i);
    const mMatch = str.match(/(\d+)\s*(?:m|min|mins?|minutes?)/i);
    if (hMatch || mMatch) {
      const h = hMatch && hMatch[1] ? parseInt(hMatch[1], 10) : 0;
      const m = mMatch && mMatch[1] ? parseInt(mMatch[1], 10) : 0;
      return formatFromMinutes(h * 60 + m);
    }
    const num = parseInt(str, 10);
    if (!isNaN(num) && num > 0) {
      return formatFromMinutes(num);
    }
    return str;
  })();

  return (
    <Link
      href={`/${locale}/services/${service.slug}`}
      className="block focus:outline-none h-full group select-none"
    >
      <Card
        hover
        className="overflow-hidden rounded-3xl border border-zinc-200/80 dark:border-zinc-800/80 bg-white dark:bg-zinc-900 shadow-2xs hover:shadow-xl transition-all duration-300 h-full flex flex-col justify-between"
      >
        <div>
          {/* ── 1. Image Banner (h-48 w-full object-cover rounded-t-2xl) ── */}
          <div className="relative h-48 w-full overflow-hidden bg-zinc-100 dark:bg-zinc-800 rounded-t-2xl">
            <ImageWithFallback
              src={imageUrl}
              alt={service.name}
              className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
              loading="lazy"
            />

            {/* ── 2. Top-Left Tags (Max 2 tags: Discount is ALWAYS first on the left, followed by Featured) ── */}
            <div className="absolute top-3 start-3 z-10 flex items-center gap-1.5 max-w-[calc(100%-60px)] flex-wrap">
              {/* Tag 1: Discount Tag (Always on Left / First) */}
              {hasDiscount && discountPercent > 0 && (
                <span className="inline-flex items-center gap-1 bg-rose-500 text-white text-[10px] font-extrabold uppercase tracking-wider px-2 py-0.5 rounded-md shadow-xs shrink-0">
                  <span>{isAr ? `خصم ${discountPercent}%` : `${discountPercent}% OFF`}</span>
                </span>
              )}

              {/* Tag 2: Featured Badge (Max 2 tags) */}
              {isFeatured && (
                <span className="inline-flex items-center gap-1.5 bg-zinc-900/90 dark:bg-white/90 text-white dark:text-zinc-900 backdrop-blur-md text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-md shadow-xs shrink-0 border border-white/10 dark:border-zinc-900/10">
                  <span className="relative flex h-1.5 w-1.5">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500" />
                  </span>
                  <span>{isAr ? 'مميز' : 'Featured'}</span>
                </span>
              )}
            </div>

            {/* ── 3. Retention Favorite Heart: Glassmorphism Icon Button on Top-Right ── */}
            <button
              type="button"
              onClick={handleHeartClick}
              className={`absolute top-3 end-3 p-2 rounded-full backdrop-blur-md border z-20 transition-all cursor-pointer shadow-xs ${
                isFav
                  ? 'bg-rose-500 text-white border-rose-500 shadow-md scale-110'
                  : 'bg-white/70 dark:bg-zinc-900/70 text-zinc-700 dark:text-zinc-200 border-white/40 dark:border-zinc-700/40 hover:scale-110 active:scale-95'
              }`}
              aria-label="Save service to favorites"
            >
              <Heart className={`w-3.5 h-3.5 ${isFav ? 'fill-current' : ''}`} />
            </button>
          </div>

          {/* ── 4. Live Data Mapping ── */}
          <div className="p-4 sm:p-5 text-start space-y-2">
            {/* Rating Row */}
            <div className="flex items-center gap-1.5">
              <div className="flex items-center gap-0.5 text-amber-400">
                <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
              </div>
              <span className="text-xs font-bold text-zinc-900 dark:text-white">
                {rating.toFixed(1)}
              </span>
              {reviewCount > 0 && (
                <span className="text-xs text-zinc-400 dark:text-zinc-500 font-medium">
                  ({reviewCount})
                </span>
              )}
              {formattedDuration && (
                <span className="ms-auto inline-flex items-center gap-1 text-[11px] font-medium text-zinc-500 dark:text-zinc-400">
                  <Clock className="w-3 h-3 text-zinc-400 dark:text-zinc-500" />
                  <span>{formattedDuration}</span>
                </span>
              )}
            </div>

            {/* Title */}
            <h3 className="font-bold text-base sm:text-lg text-zinc-900 dark:text-white line-clamp-1 group-hover:text-brand-500 transition-colors">
              {service.name}
            </h3>

            {/* Live Description */}
            {service.description && (
              <p className="text-xs text-zinc-500 dark:text-zinc-400 line-clamp-2 leading-relaxed">
                {service.description}
              </p>
            )}
          </div>
        </div>

        {/* ── 5. Conversion Pricing & Action CTA ── */}
        <div className="px-4 pb-4 sm:px-5 sm:pb-5 pt-0 flex items-center justify-between gap-3 border-t border-zinc-100 dark:border-zinc-800/80 mt-auto pt-3">
          <div>
            <div className="flex items-baseline gap-2">
              <span className="font-extrabold text-zinc-900 dark:text-white text-lg sm:text-xl">
                AED {displayPrice}
              </span>
              {hasDiscount && (
                <span className="line-through text-zinc-400 dark:text-zinc-500 text-xs sm:text-sm font-medium">
                  AED {service.price}
                </span>
              )}
            </div>
          </div>

          <button
            type="button"
            onClick={handleQuickBookClick}
            className="inline-flex items-center justify-center gap-1.5 px-4 py-2 bg-zinc-900 hover:bg-brand-500 active:bg-brand-600 dark:bg-white dark:text-zinc-950 dark:hover:bg-brand-500 dark:hover:text-white text-white rounded-xl text-xs font-bold transition-all shadow-2xs cursor-pointer shrink-0"
          >
            <CalendarCheck className="w-3.5 h-3.5" />
            <span>{isAr ? 'حجز فوري' : 'Book'}</span>
          </button>
        </div>
      </Card>
    </Link>
  );
}
