"use client";
import React, { useState } from "react";
import Breadcrumb, { BreadcrumbItem } from "@/components/breadcrumb";
import { useCart } from "@/context/CartContex";
import Image from "next/image";
import Link from "next/link";
import Metadata from "@/components/Metadata";
import OfferFormModal from "@/components/OfferFormModal";
import { OfferFormData, OfferItem, sendOffer } from "@/services/public";
import * as XLSX from 'xlsx';

const FavoritesPage = () => {
  const { clearCart, removeFromCart, cart, decreaseQuantity, increaseQuantity } = useCart();
  const [isOfferModalOpen, setIsOfferModalOpen] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState(""); // token parent'te de tutulabilir 

  const bread: BreadcrumbItem[] = [
    { href: "", label: "Teklif Listem", isCurrent: true },
  ];

  const artir = (id: string) => increaseQuantity(id);
  const azalt = (id: string) => decreaseQuantity(id);

    const exportToExcel = () => {


    let cartItems = cart.map((item) => {
      return {
        "Marka": item.brand,
        "Kategori": item.category,
        "Ürün": item.title,
        "Açıklama": item.description,
        "Adet": item.quantity,
      };
    });

    // Excel dosyası için bir çalışma sayfası oluşturun
    const worksheet = XLSX.utils.json_to_sheet(cartItems);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Teklif Listem');

    // Excel dosyasını indirin
    XLSX.writeFile(workbook, 'teklif.xlsx');
  };

  // Modal'dan gelen formu backend'e gönder
  const handleOfferSubmit = async (formData: {
    name: string;
    email: string;
    telefon: string;
    mesaj: string;
    token: string; // reCAPTCHA token modal'dan gelir
  }) => {
    if (cart.length === 0) {
      alert("Teklif listesinde ürün bulunmamaktadır!");
      return;
    }

    const offerItems: OfferItem[] = cart.map((item) => ({
      id: String(item.id),
      title: String(item.title || ""),
      brand: String(item.brand || ""),
      category: String(item.category || ""),
      quantity: Number(item.quantity || 0),
    }));

    const data: OfferFormData = {
      ...formData,
      offerItems,
    };

    const result = await sendOffer(data);

    if (result.success) {
      alert("Teklif başarıyla gönderildi!");
      clearCart(); // istersen gönderim sonrası sepeti temizle
      setIsOfferModalOpen(false);
    } else {
      alert(result.message);
    }
  };

  return (
    <>
      <Metadata seoTitle="Teklif Listem" seoDescription="Teklif Listem" />
      <Breadcrumb items={bread} />

      <div className="container py-20">
        {/* Buttons */}
        <div className="flex items-center justify-end gap-2 p-2">
          {cart.length > 0 && (
            <button
              className="flex bg-gri px-5 py-2 font-semibold gap-3 justify-center items-center"
              onClick={() => {
                if (confirm("Tüm ürünleri silmek istediğinize emin misiniz?")) {
                  clearCart();
                }
              }}
            >
              <Image src="/ico_temizle.svg" alt="" width={15} height={25} />
              Tümünü Temizle
            </button>
          )}

      {cart.length > 0 && <button className='flex    bg-gri px-5 py-2 font-semibold gap-3 justify-center items-center'
            onClick={() => exportToExcel()}>
            <Image src='/ico_excel.svg' alt='' width={15} height={25} />
            Excel'e Aktar
          </button>}

          {cart.length > 0 && (
  <button
    className="flex bg-gri px-5 py-2 font-semibold gap-3 justify-center items-center"
    onClick={() => setIsOfferModalOpen(true)} // modal açılıyor
  >
    <Image src="/ico_teklif.svg" alt="" width={15} height={25} />
    Teklifi Gönder
  </button>
)}
        </div>

        {/* Cart listesi */}
        <div className="grid grid-cols-1 gap-1">
          {cart.length < 1 && (
            <h2 className="text-lg font-semibold p-2">
              Teklif listenizde şu an herhangi bir ürün bulunmamaktadır. Yeni ürünler ekleyerek listenizi oluşturabilirsiniz.
            </h2>
          )}

          {cart.map((item) => (
            <div
              key={item.id}
              className="flex flex-col md:flex-row items-center border border-gray-200 py-2 even:bg-acikgri odd:bg-gri"
            >
              <div className="w-28 relative bg-white border min-h-28 h-full">
                {item.image && <Image src={item.image} fill className="object-contain" alt="" />}
              </div>
              <div className="flex flex-col justify-center items-start w-56 px-7">
                <span className="font-semibold">{item.brand}</span>
                <span className="text-xs">{item.category}</span>
              </div>
              <div className="px-4 gap-2 flex-1">
                <Link href={"/products/" + item.id} target="_blank" className="flex flex-col gap-1">
                  <h5 className="font-semibold">{item.title}</h5>
                  <div
                    className="text-xs line-clamp-1"
                    dangerouslySetInnerHTML={{ __html: item.description as string }}
                  />
                  <Image src="/ico_teklif.svg" width={15} height={10} alt="" />
                </Link>
              </div>
              <div className="px-8 flex items-center gap-1">
                <button onClick={() => artir(item.id)} className="bg-primary text-lg text-white px-2">+</button>
                <span className="bg-neutral-50 font-semibold py-3 px-3">{item.quantity}</span>
                <button onClick={() => azalt(item.id)} className="bg-primary text-lg text-white px-2">-</button>
                <button
                  className="px-2 bg-red-600 text-sm py-1 text-white font-extrabold"
                  onClick={() => {
                    if (confirm("Bu ürünü sepetten çıkarmak istediğinize emin misiniz?")) {
                      removeFromCart(item.id);
                    }
                  }}
                >
                  X
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Teklif Form Modal */}
      <OfferFormModal
        isOpen={isOfferModalOpen}
        onClose={() => setIsOfferModalOpen(false)}
        onSubmit={handleOfferSubmit} // cart + form data backend'e gönderilecek
        offerItems={cart.map((item) => ({
          id: String(item.id),
          title: String(item.title || ""),
          brand: String(item.brand || ""),
          category: String(item.category || ""),
          quantity: Number(item.quantity || 0),
        }))} // cart ürünleri modal’a props olarak gönderiliyor
      />
    </>
  );
};

export default FavoritesPage;