'use client';
import { useState } from 'react';
import AppLayout from '@/components/AppLayout';
import Link from 'next/link';
import ImageGallery from './ImageGallery';
import PricingTable from './PricingTable';
import CartDrawer from '@/components/CartDrawer';
import { useCart, PaymentMethod } from '@/lib/cartContext';
import { saveNegotiationRequest } from '@/lib/negotiationState';

const NEGOTIATION_THRESHOLD = 300;

const saleTypeBadge: Record<string, { label: string; color: string; bg: string }> = {
  direct:  { label: 'مباشر', color: '#fff', bg: '#00C2A8' },
  deferred:{ label: 'بالآجل', color: '#1B1D3A', bg: '#F5A623' },
  negotiable: { label: 'قابل للتفاوض', color: '#fff', bg: '#3B82F6' },
};

const CONTRACT_TYPES: { value: PaymentMethod; label: string; desc: string; icon: string; color: string; bg: string; border: string }[] = [
  { value: 'immediate', label: 'فوري', desc: 'الدفع عند الاستلام', icon: 'ri-flashlight-line', color: '#059669', bg: '#D1FAE5', border: '#6EE7B7' },
  { value: 'deferred', label: 'آجل', desc: 'الدفع بعد مدة متفق عليها', icon: 'ri-calendar-schedule-line', color: '#D97706', bg: '#FEF3C7', border: '#FCD34D' },
  { value: 'installment', label: 'تصريف', desc: 'دفع على دفعات متعددة', icon: 'ri-exchange-funds-line', color: '#7C3AED', bg: '#EDE9FE', border: '#C4B5FD' },
];

export default function ProductDetail({ productId }: { productId: string }) {
  const [qty, setQty] = useState(10);
  const [selectedContract, setSelectedContract] = useState<PaymentMethod>('immediate');
  const [cartOpen, setCartOpen] = useState(false);
  const [addedAnim, setAddedAnim] = useState(false);
  const [negotiationPrice, setNegotiationPrice] = useState('');
  const [negotiationError, setNegotiationError] = useState('');
  const { addItem, getItemCount } = useCart();

  const saleType = ['direct', 'deferred', 'negotiable'][Number(productId) % 3] ?? 'direct';
  const badge = saleTypeBadge[saleType];
  const isNegotiationMode = qty >= NEGOTIATION_THRESHOLD;

  const estimatedTotal = isNegotiationMode && negotiationPrice
    ? qty * parseFloat(negotiationPrice)
    : qty * 2850;

  function handleAddToCart() {
    if (isNegotiationMode) {
      const price = parseFloat(negotiationPrice);
      if (!negotiationPrice || isNaN(price) || price <= 0) {
        setNegotiationError('يرجى إدخال سعر التفاوض المقترح');
        return;
      }
      setNegotiationError('');
      addItem({
        productId,
        name: 'حديد التسليح المشكّل (طلب تفاوض)',
        qty,
        minQty: 10,
        unit: 'طن',
        price,
        paymentMethod: selectedContract,
        supplierId: '1',
        supplierName: 'شركة الفولاذ العربي المتحدة',
        image: 'https://readdy.ai/api/search-image?query=steel%20reinforcement%20bars%20industrial%20product%20photography%20clean%20white%20background%20professional&width=200&height=200&seq=cart-product-1&orientation=squarish',
      });
      setAddedAnim(true);
      setTimeout(() => {
        setAddedAnim(false);
        setCartOpen(true);
      }, 600);
      return;
    }
    addItem({
      productId,
      name: 'حديد التسليح المشكّل',
      qty,
      minQty: 10,
      unit: 'طن',
      price: 2850,
      paymentMethod: selectedContract,
      supplierId: '1',
      supplierName: 'شركة الفولاذ العربي المتحدة',
      image: 'https://readdy.ai/api/search-image?query=steel%20reinforcement%20bars%20industrial%20product%20photography%20clean%20white%20background%20professional&width=200&height=200&seq=cart-product-1&orientation=squarish',
    });
    setAddedAnim(true);
    setTimeout(() => {
      setAddedAnim(false);
      setCartOpen(true);
    }, 600);
  }

  const cartCount = getItemCount();

  return (
    <AppLayout>
      <div dir="rtl" className="pb-28">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between mb-5 gap-3">
          <div className="flex items-center gap-1 text-sm text-[#6B6B66] overflow-hidden">
            <span className="text-[#030772] font-medium whitespace-nowrap hidden md:inline">حديد التسليح المشكّل</span>
            <i className="ri-arrow-left-s-line text-[#8B94EC] hidden md:inline"></i>
            <Link href="/suppliers/1" className="hover:text-[#030772] cursor-pointer transition-colors whitespace-nowrap hidden sm:inline">شركة الفولاذ العربي المتحدة</Link>
            <i className="ri-arrow-left-s-line text-[#8B94EC] hidden sm:inline"></i>
            <Link href="/search" className="hover:text-[#030772] cursor-pointer transition-colors whitespace-nowrap">الموردون</Link>
            <i className="ri-arrow-left-s-line text-[#8B94EC]"></i>
            <Link href="/" className="hover:text-[#030772] cursor-pointer transition-colors whitespace-nowrap">الرئيسية</Link>
          </div>
          {cartCount > 0 && (
            <button
              onClick={() => setCartOpen(true)}
              className="flex items-center gap-2 bg-[#030772] hover:bg-[#0A0FAD] text-white px-4 py-2 rounded-xl text-sm font-bold transition-colors cursor-pointer whitespace-nowrap self-start"
            >
              <div className="relative w-5 h-5 flex items-center justify-center">
                <i className="ri-shopping-cart-2-line text-base"></i>
                <span className="absolute -top-1.5 -left-1.5 w-4 h-4 flex items-center justify-center bg-[#F5A623] text-[#1B1D3A] rounded-full text-[9px] font-black">{cartCount}</span>
              </div>
              عرض السلة
            </button>
          )}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 md:gap-6 mb-6">
          <div className="flex flex-col gap-5">
            <ImageGallery />
            <PricingTable />
          </div>

          <div className="flex flex-col gap-5">
            <div className="bg-white rounded-xl border border-[#C8CCF7] p-6" style={{ boxShadow: '0 2px 8px rgba(3,7,114,0.08)' }}>
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-2">
                  <span className="text-xs font-medium px-3 py-1 rounded-full text-white whitespace-nowrap" style={{ background: badge.bg, color: badge.color }}>
                    {badge.label}
                  </span>
                  <span className="text-xs bg-[#D1FAE5] text-[#065F46] px-2.5 py-1 rounded-full font-medium">متوفر</span>
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-[#030772] text-right mb-1">حديد التسليح المشكّل</h1>
                  <p className="text-sm text-[#6B6B66] text-right">رمز المنتج: ST-REF-001</p>
                </div>
              </div>

              <div className="flex items-end justify-between mb-4 pb-4 border-b border-[#EEEFFE]">
                <div className="text-left">
                  <p className="text-xs text-[#6B6B66]">سعر بداية من</p>
                  <p className="text-xs text-[#8B94EC]">للطلبيات فوق ١٠٠ طن</p>
                </div>
                <div className="text-right">
                  <div className="flex items-baseline gap-1">
                    <span className="text-sm text-[#6B6B66]">ريال/طن</span>
                    <span className="text-3xl font-bold text-[#030772]">٢,٨٥٠</span>
                  </div>
                  <p className="text-xs text-[#00C2A8] font-medium mt-0.5">يشمل ضريبة القيمة المضافة ١٥٪</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 mb-4">
                <InfoChip icon="ri-stack-line" label="المخزون المتاح" value="٢٣٠ طناً" />
                <InfoChip icon="ri-scales-line" label="الحد الأدنى للطلب" value="١٠ أطنان" />
                <InfoChip icon="ri-truck-line" label="وقت التوصيل" value="٧–١٤ يوم عمل" />
                <InfoChip icon="ri-map-pin-line" label="الموقع" value="المنطقة الصناعية، الرياض" />
              </div>

              <div className="bg-[#F4F4FB] rounded-xl p-4 mb-4">
                <p className="text-sm font-semibold text-[#030772] text-right mb-2">حدد الكمية المطلوبة (طن)</p>
                <div className="flex items-center justify-end gap-3">
                  <div className="text-left">
                    <p className="text-xs text-[#6B6B66]">الإجمالي التقديري</p>
                    {isNegotiationMode && negotiationPrice && !isNaN(parseFloat(negotiationPrice)) ? (
                      <p className="text-base font-bold text-[#030772]">{(qty * parseFloat(negotiationPrice)).toLocaleString('ar-SA')} ريال</p>
                    ) : isNegotiationMode ? (
                      <p className="text-base font-bold text-[#F5A623]">أدخل سعر التفاوض</p>
                    ) : (
                      <p className="text-base font-bold text-[#030772]">{(qty * 2850).toLocaleString('ar-SA')} ريال</p>
                    )}
                  </div>
                  <div className="flex items-center gap-3">
                    <button onClick={() => setQty(Math.max(10, qty - 10))} className="w-9 h-9 flex items-center justify-center bg-white border border-[#C8CCF7] hover:border-[#030772] rounded-lg cursor-pointer transition-colors">
                      <i className="ri-subtract-line text-[#030772]"></i>
                    </button>
                    <span className="text-xl font-bold text-[#030772] w-12 text-center">{qty}</span>
                    <button onClick={() => setQty(qty + 10)} className="w-9 h-9 flex items-center justify-center bg-white border border-[#C8CCF7] hover:border-[#030772] rounded-lg cursor-pointer transition-colors">
                      <i className="ri-add-line text-[#030772]"></i>
                    </button>
                  </div>
                </div>

                {isNegotiationMode && (
                  <div className="mt-3 space-y-3">
                    <div className="flex items-center gap-2 bg-[#FEF3C7] border border-[#FCD34D] rounded-lg px-3 py-2">
                      <div className="w-4 h-4 flex items-center justify-center flex-shrink-0">
                        <i className="ri-shake-hands-line text-[#D97706] text-sm"></i>
                      </div>
                      <p className="text-xs text-[#92400E] font-medium">الكميات من 300 طن فأكثر — أدخل سعرك المقترح للتفاوض</p>
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-[#030772] text-right mb-1.5">
                        سعر التفاوض المقترح (ريال/طن)
                      </label>
                      <div className="relative">
                        <input
                          type="number"
                          value={negotiationPrice}
                          onChange={(e) => {
                            setNegotiationPrice(e.target.value);
                            setNegotiationError('');
                          }}
                          placeholder="مثال: 2600"
                          className="w-full bg-white border-2 border-[#C8CCF7] focus:border-[#030772] rounded-xl px-4 py-3 text-sm text-right text-[#1B1D3A] outline-none transition-colors placeholder:text-[#B0B8E0]"
                          style={{ direction: 'rtl' }}
                        />
                        <div className="absolute left-3 top-1/2 -translate-y-1/2 flex items-center gap-1">
                          <span className="text-xs text-[#8B94EC] font-medium">ريال</span>
                          <div className="w-4 h-4 flex items-center justify-center">
                            <i className="ri-price-tag-3-line text-[#8B94EC] text-sm"></i>
                          </div>
                        </div>
                      </div>
                      {negotiationError && (
                        <p className="text-xs text-red-500 text-right mt-1 flex items-center justify-end gap-1">
                          <span>{negotiationError}</span>
                          <i className="ri-error-warning-line"></i>
                        </p>
                      )}
                      {negotiationPrice && !isNaN(parseFloat(negotiationPrice)) && parseFloat(negotiationPrice) > 0 && (
                        <div className="mt-2 flex items-center justify-between bg-[#EEEFFE] rounded-lg px-3 py-2">
                          <span className="text-xs font-bold text-[#030772]">{(qty * parseFloat(negotiationPrice)).toLocaleString('ar-SA')} ريال</span>
                          <span className="text-xs text-[#6B6B66]">الإجمالي المقترح ({qty} طن)</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              <div className="mb-4">
                <p className="text-sm font-semibold text-[#030772] text-right mb-3">نوع العقد</p>
                <div className="flex flex-col gap-2">
                  {CONTRACT_TYPES.map((ct) => (
                    <button
                      key={ct.value}
                      onClick={() => setSelectedContract(ct.value)}
                      className={`flex items-center gap-3 w-full p-3 rounded-xl border-2 transition-all cursor-pointer ${
                        selectedContract === ct.value
                          ? 'border-current'
                          : 'border-[#EEEFFE] hover:border-[#C8CCF7] bg-[#FAFAFA]'
                      }`}
                      style={selectedContract === ct.value ? {
                        borderColor: ct.border,
                        background: ct.bg,
                      } : {}}
                    >
                      <div className="flex-1 text-right">
                        <div className="flex items-center justify-end gap-2">
                          {selectedContract === ct.value && (
                            <div className="w-4 h-4 flex items-center justify-center">
                              <i className="ri-check-line text-sm" style={{ color: ct.color }}></i>
                            </div>
                          )}
                          <p className="text-sm font-bold" style={{ color: selectedContract === ct.value ? ct.color : '#1B1D3A' }}>{ct.label}</p>
                        </div>
                        <p className="text-xs text-[#6B6B66] mt-0.5">{ct.desc}</p>
                      </div>
                      <div className="w-9 h-9 flex items-center justify-center rounded-lg" style={{ background: ct.bg }}>
                        <i className={`${ct.icon} text-base`} style={{ color: ct.color }}></i>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              <button
                onClick={handleAddToCart}
                disabled={addedAnim}
                className={`w-full font-bold py-4 rounded-xl text-base transition-all cursor-pointer whitespace-nowrap flex items-center justify-center gap-2 ${
                  addedAnim
                    ? 'bg-[#059669] text-white scale-95'
                    : isNegotiationMode
                    ? 'bg-[#F5A623] hover:bg-[#D97706] text-[#1B1D3A]'
                    : 'bg-[#030772] hover:bg-[#0A0FAD] text-white'
                }`}
              >
                <div className="w-5 h-5 flex items-center justify-center">
                  <i className={`text-lg ${addedAnim ? 'ri-check-line' : isNegotiationMode ? 'ri-shake-hands-line' : 'ri-shopping-cart-2-line'}`}></i>
                </div>
                {addedAnim
                  ? 'تمت الإضافة!'
                  : isNegotiationMode
                  ? `إضافة طلب التفاوض للسلة — ${qty} طن`
                  : `إضافة للسلة — ${qty} طن`}
              </button>
            </div>

            <div className="bg-white rounded-xl border border-[#C8CCF7] p-5" style={{ boxShadow: '0 2px 8px rgba(3,7,114,0.08)' }}>
              <p className="text-sm font-semibold text-[#030772] text-right mb-3">المورد</p>
              <div className="flex items-center justify-between">
                <Link href="/suppliers/1">
                  <button className="text-xs text-[#3D4DE0] hover:text-[#030772] cursor-pointer transition-colors whitespace-nowrap">
                    عرض الملف الكامل ←
                  </button>
                </Link>
                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <p className="text-sm font-semibold text-[#1B1D3A]">شركة الفولاذ العربي المتحدة</p>
                    <div className="flex items-center justify-end gap-1">
                      <i className="ri-map-pin-line text-[#8B94EC] text-xs"></i>
                      <span className="text-xs text-[#6B6B66]">الرياض</span>
                      <span className="text-[#C8CCF7] mx-1">|</span>
                      <i className="ri-star-fill text-[#F5A623] text-xs"></i>
                      <span className="text-xs text-[#1B1D3A] font-medium">4.9</span>
                    </div>
                  </div>
                  <div className="w-10 h-10 rounded-xl bg-[#030772] flex items-center justify-center font-bold text-white">
                    ف
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#C8CCF7] p-5 mb-6" style={{ boxShadow: '0 2px 8px rgba(3,7,114,0.08)' }}>
          <p className="text-base font-semibold text-[#030772] text-right mb-4">المواصفات الفنية</p>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {[
              { k: 'المعيار', v: 'SASO 2579 / ASTM A615' },
              { k: 'درجة الصلابة', v: 'Grade 60 (420 MPa)' },
              { k: 'الأقطار المتاحة', v: '8، 10، 12، 16، 20، 25 ملم' },
              { k: 'طول القضيب', v: '12 متر (قياسي)' },
              { k: 'الكربون الكلي', v: '≤ 0.55٪' },
              { k: 'شهادة المطابقة', v: 'SASO — صادرة حديثاً' },
            ].map((spec, i) => (
              <div key={i} className="bg-[#F4F4FB] rounded-xl p-4 text-right">
                <p className="text-xs text-[#6B6B66] mb-1">{spec.k}</p>
                <p className="text-sm font-semibold text-[#1B1D3A]">{spec.v}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#C8CCF7] p-6 mb-6" style={{ boxShadow: '0 2px 8px rgba(3,7,114,0.08)' }}>
          <p className="text-base font-semibold text-[#030772] text-right mb-3">وصف المنتج</p>
          <p className="text-sm text-[#1B1D3A] text-right leading-relaxed">
            حديد التسليح المشكّل (القضبان المضلعة) من إنتاج شركة الفولاذ العربي المتحدة، مطابق لمتطلبات المواصفة السعودية SASO 2579 والمعيار الأمريكي ASTM A615. يُستخدم في تسليح الأعمدة والأسقف والجدران الإنشائية لمشاريع البناء السكنية والتجارية والصناعية.
          </p>
          <p className="text-sm text-[#1B1D3A] text-right leading-relaxed mt-3">
            يتميز المنتج بارتفاع نسبة الشد، ومقاومة عالية للصدأ، وسهولة اللحام والتشكيل. يتوفر في أقطار متعددة تبدأ من 8 ملم وتصل إلى 32 ملم، بأطوال قياسية 12 متر أو حسب الطلب. يأتي كل دفعة مع شهادة مطابقة صادرة من SASO وتقرير اختبارات معمل معتمد.
          </p>
        </div>

        <div className="bg-[#EEEFFE] border border-[#C8CCF7] rounded-xl p-5 flex items-start gap-4">
          <div className="flex-1 text-right">
            <p className="text-sm font-semibold text-[#030772] mb-1">معلومات الشحن والتوصيل</p>
            <p className="text-sm text-[#1B1D3A]">التوصيل متاح لجميع مناطق المملكة العربية السعودية. الرياض وجدة والدمام خلال 3–5 أيام، المناطق الأخرى 7–14 يوم عمل. رسوم الشحن تُحسب حسب الكمية والموقع.</p>
          </div>
          <div className="w-12 h-12 flex items-center justify-center bg-[#030772] rounded-xl flex-shrink-0">
            <i className="ri-truck-line text-white text-xl"></i>
          </div>
        </div>
      </div>

      <CartDrawer isOpen={cartOpen} onClose={() => setCartOpen(false)} supplierId="1" />
    </AppLayout>
  );
}

function InfoChip({ icon, label, value }: { icon: string; label: string; value: string }) {
  return (
    <div className="flex items-center gap-3 bg-[#F4F4FB] rounded-lg p-3">
      <div className="flex-1 text-right min-w-0">
        <p className="text-xs text-[#6B6B66] truncate">{label}</p>
        <p className="text-sm font-semibold text-[#1B1D3A] truncate">{value}</p>
      </div>
      <div className="w-8 h-8 flex items-center justify-center bg-[#EEEFFE] rounded-lg flex-shrink-0">
        <i className={`${icon} text-[#030772] text-sm`}></i>
      </div>
    </div>
  );
}
