"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { fetchWrapper } from "@/helpers";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";

import { Info, Newspaper, CalendarSync, ShieldCheck, Ship, Box } from "lucide-react";

import { getProductLanguageDirect, useT } from "@/context/I18nContext"; 

const MySwal = withReactContent(Swal);

const parseItems = (items) => {
	if (!items) return [];
	if (typeof items === "string") {
		try {
			return JSON.parse(items);
		} catch {
			return [];
		}
	}
	if (Array.isArray(items)) return items;
	return [];
};

export async function openConformitateForm(order) {
	const selectedProducts = new Set();
	const items = parseItems(order.items);
	const productHtml = items
		.map(
			(item) => `
      <div
        class="conformitate-item"
        data-id="${item.id}"
      >
        <div class="conformitate-item-check">
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none">
            <path d="M16.6667 5L7.50004 14.1667L3.33337 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <div class="conformitate-item-content">
          <h4 class="conformitate-item-name">${item.name}</h4>
          <div class="conformitate-item-meta">
            <span class="conformitate-item-sku">${item.sku}</span>
            <span class="conformitate-item-price">${item.price} RON</span>
          </div>
        </div>
      </div>`,
		)
		.join("");

	const { value: formValues } = await MySwal.fire({
		title: "",
		width: "900px",
		background: "#ffffff",
		color: "#000000",
		showConfirmButton: true,
		showCancelButton: true,
		confirmButtonText: "Trimite cererea",
		cancelButtonText: "Anulează",
		customClass: {
			popup: "premium-conformitate-popup",
			confirmButton: "premium-confirm-btn",
			cancelButton: "premium-cancel-btn",
			htmlContainer: "premium-html-container",
		},
		html: `
      <style>
        .premium-conformitate-popup {
          border-radius: 16px !important;
          padding: 0 !important;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15) !important;
        }
        
        .premium-html-container {
          margin: 0 !important;
          padding: 0 !important;
        }
        
        .conformitate-form-container {
          text-align: left;
          max-height: 80vh;
          overflow-y: auto;
          padding: 40px;
        }
        
        .conformitate-form-container::-webkit-scrollbar {
          width: 8px;
        }
        
        .conformitate-form-container::-webkit-scrollbar-track {
          background: #f5f5f5;
          border-radius: 4px;
        }
        
        .conformitate-form-container::-webkit-scrollbar-thumb {
          background: #d0d0d0;
          border-radius: 4px;
        }
        
        .conformitate-form-container::-webkit-scrollbar-thumb:hover {
          background: #b0b0b0;
        }
        
        .conformitate-form-header {
          margin-bottom: 32px;
          padding-bottom: 24px;
          border-bottom: 1px solid #e5e5e5;
        }
        
        .conformitate-form-title {
          font-size: 32px;
          font-weight: 700;
          margin: 0 0 16px 0;
          color: #000000;
        }
        
        .conformitate-form-subtitle {
          font-size: 15px;
          color: #666666;
          margin: 0;
          line-height: 1.6;
        }
        
        .info-box {
          background: #f0f9ff;
          border: 2px solid #bae6fd;
          border-radius: 12px;
          padding: 20px;
          margin-bottom: 32px;
        }
        
        .info-box-content {
          display: flex;
          align-items: flex-start;
          gap: 16px;
        }
        
        .info-icon {
          width: 24px;
          height: 24px;
          background: #0ea5e9;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-weight: 700;
          flex-shrink: 0;
          margin-top: 2px;
        }
        
        .info-text {
          font-size: 14px;
          color: #0c4a6e;
          line-height: 1.6;
          margin: 0;
        }
        
        .conformitate-section {
          margin-bottom: 32px;
        }
        
        .section-header {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 16px;
        }
        
        .section-number {
          width: 32px;
          height: 32px;
          background: #000000;
          color: #ffffff;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 16px;
          flex-shrink: 0;
        }
        
        .section-title {
          font-size: 20px;
          font-weight: 600;
          margin: 0;
          color: #000000;
        }
        
        .section-description {
          font-size: 14px;
          color: #666666;
          margin: 8px 0 0 44px;
        }
        
        .product-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
          gap: 12px;
          margin-top: 16px;
        }
        
        .conformitate-item {
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 12px;
          padding: 16px;
          cursor: pointer;
          transition: all 0.2s ease;
          position: relative;
          display: flex;
          align-items: flex-start;
          gap: 12px;
        }
        
        .conformitate-item:hover {
          border-color: #d0d0d0;
          background: #f5f5f5;
        }
        
        .conformitate-item.selected {
          border-color: #000000;
          background: #f5f5f5;
        }
        
        .conformitate-item-check {
          width: 20px;
          height: 20px;
          border: 2px solid #d0d0d0;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #ffffff;
          background: transparent;
          transition: all 0.2s ease;
          flex-shrink: 0;
          margin-top: 2px;
        }
        
        .conformitate-item-check svg {
          opacity: 0;
          transform: scale(0.5);
          transition: all 0.2s ease;
        }
        
        .conformitate-item.selected .conformitate-item-check {
          background: #000000;
          border-color: #000000;
        }
        
        .conformitate-item.selected .conformitate-item-check svg {
          opacity: 1;
          transform: scale(1);
        }
        
        .conformitate-item-content {
          flex: 1;
          min-width: 0;
        }
        
        .conformitate-item-name {
          font-size: 15px;
          font-weight: 600;
          margin: 0 0 8px 0;
          color: #000000;
          line-height: 1.3;
        }
        
        .conformitate-item-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;
        }
        
        .conformitate-item-sku {
          font-size: 13px;
          color: #666666;
        }
        
        .conformitate-item-price {
          font-size: 15px;
          font-weight: 700;
          color: #000000;
        }
        
        .form-group {
          margin-bottom: 20px;
        }
        
        .form-label {
          display: block;
          font-size: 14px;
          font-weight: 600;
          color: #000000;
          margin-bottom: 8px;
        }
        
        .form-input {
          width: 100%;
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 10px;
          padding: 14px 16px;
          font-size: 15px;
          color: #000000;
          transition: all 0.2s ease;
          font-family: inherit;
        }
        
        .form-input:focus {
          outline: none;
          border-color: #000000;
          background: #ffffff;
        }
        
        .form-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 16px;
        }
        
        .confirmation-section {
          margin-top: 32px;
          padding: 24px;
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 12px;
        }
        
        .confirmation-label {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          cursor: pointer;
          user-select: none;
        }
        
        .confirmation-checkbox {
          width: 20px;
          height: 20px;
          border: 2px solid #d0d0d0;
          border-radius: 6px;
          flex-shrink: 0;
          margin-top: 2px;
          cursor: pointer;
          accent-color: #000000;
        }
        
        .confirmation-text {
          font-size: 14px;
          color: #333333;
          line-height: 1.5;
        }
        
        .premium-confirm-btn {
          background: #000000 !important;
          color: #ffffff !important;
          border: none !important;
          border-radius: 10px !important;
          padding: 14px 32px !important;
          font-size: 15px !important;
          font-weight: 600 !important;
          transition: all 0.2s ease !important;
        }
        
        .premium-confirm-btn:hover {
          background: #333333 !important;
          transform: translateY(-1px);
        }
        
        .premium-cancel-btn {
          background: transparent !important;
          color: #666666 !important;
          border: 2px solid #d0d0d0 !important;
          border-radius: 10px !important;
          padding: 14px 32px !important;
          font-size: 15px !important;
          font-weight: 600 !important;
          transition: all 0.2s ease !important;
        }
        
        .premium-cancel-btn:hover {
          border-color: #b0b0b0 !important;
          color: #333333 !important;
        }
        
        @media (max-width: 768px) {
          .conformitate-form-container {
            padding: 24px;
          }
          
          .conformitate-form-title {
            font-size: 24px;
          }
          
          .product-grid {
            grid-template-columns: 1fr;
          }
          
          .form-grid {
            grid-template-columns: 1fr;
          }
          
          .section-title {
            font-size: 18px;
          }
        }
      </style>
      
      <div class="conformitate-form-container">
        <div class="conformitate-form-header">
          <h2 class="conformitate-form-title">Cerere certificat de conformitate</h2>
          <p class="conformitate-form-subtitle">Completează formularul pentru a solicita certificatul de conformitate</p>
        </div>
        
        <div class="info-box">
          <div class="info-box-content">
            <div class="info-icon">i</div>
            <p class="info-text">
              Certificatele de conformitate se eliberează doar la cerere, de către furnizor. Vă rugăm să completați formularul de mai jos pentru a da curs solicitării dumneavoastră. <strong>Veți primi certificatul de conformitate pentru produsele selectate pe email în termen de 7 zile de la data preluării solicitării.</strong>
            </p>
          </div>
        </div>
        
        <div class="conformitate-section">
          <div class="section-header">
            <div class="section-number">1</div>
            <h3 class="section-title">Selectează produsele</h3>
          </div>
          <p class="section-description">Alege produsele pentru care dorești certificat de conformitate</p>
          <div class="product-grid" id="product-list">${productHtml}</div>
        </div>
        
        <div class="conformitate-section">
          <div class="section-header">
            <div class="section-number">2</div>
            <h3 class="section-title">Datele tale de contact</h3>
          </div>
          <p class="section-description">Aceste informații vor fi folosite pentru trimiterea certificatului</p>
          <div class="form-grid">
            <div class="form-group">
              <label class="form-label" for="customerName">Nume complet *</label>
              <input id="customerName" class="form-input" placeholder="Introdu numele complet" value="${
				order.pf_prenume.length >= 1
					? order.pf_nume_familie || order.pf_prenume || ""
					: order.pj_nume_firma || ""
			}" />
            </div>
            <div class="form-group">
              <label class="form-label" for="customerEmail">Email *</label>
              <input id="customerEmail" type="email" class="form-input" placeholder="exemplu@email.com" value="${
				order.pf_prenume.length >= 1 ? order.pf_email || "" : order.pj_email || ""
			}" />
            </div>
            <div class="form-group">
              <label class="form-label" for="customerPhone">Telefon *</label>
              <input id="customerPhone" type="tel" class="form-input" placeholder="07XX XXX XXX" value="${
				order.pf_prenume.length >= 1 ? order.pf_numar_telefon || "" : order.pj_numar_telefon || ""
			}" />
            </div>
          </div>
        </div>
        
        <div class="confirmation-section">
          <label class="confirmation-label">
            <input type="checkbox" id="confirm" class="confirmation-checkbox" />
            <span class="confirmation-text">
              Confirm că datele introduse sunt corecte și doresc să primesc certificatul de conformitate pentru produsele selectate. Înțeleg că certificatul va fi trimis pe email în termen de 7 zile lucrătoare.
            </span>
          </label>
        </div>
      </div>
    `,
		preConfirm: () => {
			const customerName = document.getElementById("customerName").value.trim();
			const customerEmail = document.getElementById("customerEmail").value.trim();
			const customerPhone = document.getElementById("customerPhone").value.trim();
			const confirm = document.getElementById("confirm").checked;

			if (selectedProducts.size === 0) {
				return Swal.showValidationMessage("Selectează cel puțin un produs.");
			}
			if (!customerName) {
				return Swal.showValidationMessage("Introduceți numele complet.");
			}
			if (!customerEmail) {
				return Swal.showValidationMessage("Introduceți adresa de email.");
			}
			if (!customerPhone) {
				return Swal.showValidationMessage("Introduceți numărul de telefon.");
			}
			if (!confirm) {
				return Swal.showValidationMessage("Trebuie să confirmi declarația.");
			}

			// Validare email simplă
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			if (!emailRegex.test(customerEmail)) {
				return Swal.showValidationMessage("Adresa de email nu este validă.");
			}

			return {
				selectedItems: Array.from(selectedProducts),
				customerName,
				customerEmail,
				customerPhone,
				createdAt: new Date().toISOString(),
			};
		},
		didOpen: () => {
			// Product selection
			document.querySelectorAll(".conformitate-item").forEach((el) => {
				el.addEventListener("click", () => {
					const id = parseInt(el.dataset.id);
					if (selectedProducts.has(id)) {
						selectedProducts.delete(id);
						el.classList.remove("selected");
					} else {
						selectedProducts.add(id);
						el.classList.add("selected");
					}
				});
			});
		},
	});

	if (formValues) {
		const conformitateData = {
			orderID: order.id,
			customer: {
				name: formValues.customerName,
				email: formValues.customerEmail,
				phone: formValues.customerPhone,
			},
			selectedItems: formValues.selectedItems,
			createdAt: formValues.createdAt,
		};

		const conformitateResponse = await fetchWrapper.post("/api/users/conformitate", conformitateData);

		if (conformitateResponse.success === true) {
			Swal.fire({
				title: "Trimis!",
				text: "Cererea pentru certificatul de conformitate a fost înregistrată cu succes. Veți primi certificatul pe email în termen de 7 zile lucrătoare.",
				icon: "success",
				background: "#ffffff",
				color: "#000000",
				confirmButtonColor: "#000000",
				customClass: {
					confirmButton: "premium-confirm-btn",
				},
			});
		} else {
			Swal.fire({
				title: "Eroare",
				text:
					conformitateResponse.error ||
					"A apărut o eroare la trimiterea cererii. Te rugăm să încerci din nou.",
				icon: "error",
				background: "#ffffff",
				color: "#000000",
				confirmButtonColor: "#000000",
				customClass: {
					confirmButton: "premium-confirm-btn",
				},
			});
		}

		return conformitateData;
	}
}

export async function openOrderDetails(order, t) {
	const items = parseItems(order.items);
	const isPF = order.pf_prenume?.length >= 1;

	const statusColors = {
		paid: { bg: "#f0fdf4", color: "#16a34a", border: "#bbf7d0", label: "Plătit" },
		pending: { bg: "#fffbeb", color: "#d97706", border: "#fde68a", label: "În așteptare" },
		cancelled: { bg: "#fef2f2", color: "#dc2626", border: "#fecaca", label: "Anulat" },
		shipped: { bg: "#eff6ff", color: "#2563eb", border: "#bfdbfe", label: "Expediat" },
		delivered: { bg: "#f0fdf4", color: "#16a34a", border: "#bbf7d0", label: "Livrat" },
	};
	const statusStyle = statusColors[order.status] || {
		bg: "#f5f5f5",
		color: "#666",
		border: "#e5e5e5",
		label: order.status,
	};

	const total = (items.reduce((sum, item) => sum + parseFloat(item.price) * item.quantity, 0) + 25).toFixed(2);

     const moneda = t("order_details_moneda"); 

	const productsHtml = items
		.map((item) => {
			const img = item.images?.split("|")[0] || "";
			return `
        <div style="display:flex;align-items:center;gap:16px;padding:16px;background:#fafafa;border:2px solid #e5e5e5;border-radius:12px;margin-bottom:10px;">
            ${img ? `<img src="${img}" alt="${getProductLanguageDirect(item, t)}" style="width:72px;height:72px;object-fit:cover;border-radius:8px;flex-shrink:0;border:1px solid #e5e5e5;" />` : ""}
            <div style="flex:1;min-width:0;text-align:left;">
                <div style="font-size:14px;font-weight:600;color:#000;line-height:1.4;margin-bottom:6px;">${getProductLanguageDirect(item, t)}</div>
                <div style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
                    <span style="font-size:12px;color:#888;background:#f0f0f0;padding:2px 8px;border-radius:20px;">SKU: ${item.sku}</span>
                    <span style="font-size:12px;color:#888;">${t("order_details_cant")} <b style="color:#000">${item.quantity}</b></span>
                    <span style="font-size:14px;font-weight:700;color:#000;">${item.price} ${moneda}</span>
                    ${item.priceReduced ? `<span style="font-size:12px;color:#dc2626;text-decoration:line-through;">${item.priceReduced} ${moneda}</span>` : ""}
                </div>
            </div>
        </div>`;
		})
		.join("");

	await MySwal.fire({
		title: "",
		width: "860px",
		background: "#ffffff",
		color: "#000000",
		showConfirmButton: true,
		confirmButtonText: t("order_details_inchide"),
		showCancelButton: false,
		customClass: {
			popup: "order-detail-popup",
			confirmButton: "premium-confirm-btn",
			htmlContainer: "premium-html-container",
		},
		html: `
        <style>
            .order-detail-popup {
                border-radius: 16px !important;
                padding: 0 !important;
                box-shadow: 0 20px 60px rgba(0,0,0,0.15) !important;
            }
            .order-detail-container {
                text-align: left;
                max-height: 80vh;
                overflow-y: auto;
                padding: 40px;
            }
            .order-detail-container::-webkit-scrollbar { width: 8px; }
            .order-detail-container::-webkit-scrollbar-track { background: #f5f5f5; border-radius: 4px; }
            .order-detail-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }
            .od-header {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                margin-bottom: 28px;
                padding-bottom: 24px;
                border-bottom: 1px solid #e5e5e5;
                flex-wrap: wrap;
                gap: 12px;
            }
            .od-title { font-size: 28px; font-weight: 700; margin: 0 0 6px 0; color: #000; }
            .od-date { font-size: 14px; color: #888; }
            .od-status {
                padding: 8px 18px;
                border-radius: 20px;
                font-size: 13px;
                font-weight: 700;
                border: 2px solid ${statusStyle.border};
                background: ${statusStyle.bg};
                color: ${statusStyle.color};
                white-space: nowrap;
            }
            .od-section { margin-bottom: 28px; }
            .od-section-title {
                font-size: 13px;
                font-weight: 700;
                text-transform: uppercase;
                letter-spacing: 0.08em;
                color: #999;
                margin-bottom: 14px;
            }
            .od-info-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 12px;
            }
            .od-info-card {
                background: #fafafa;
                border: 2px solid #e5e5e5;
                border-radius: 12px;
                padding: 16px;
            }
            .od-info-label { font-size: 12px; color: #999; margin-bottom: 4px; }
            .od-info-value { font-size: 14px; font-weight: 600; color: #000; line-height: 1.4; }
            .od-total-row {
                display: flex;
                justify-content: space-between;
                padding: 10px 0;
                font-size: 14px;
                color: #555;
                border-bottom: 1px solid #f0f0f0;
            }
            .od-total-final {
                display: flex;
                justify-content: space-between;
                padding: 14px 0 0 0;
                font-size: 18px;
                font-weight: 700;
                color: #000;
            }
            .premium-confirm-btn {
                background: #000 !important;
                color: #fff !important;
                border: none !important;
                border-radius: 10px !important;
                padding: 14px 40px !important;
                font-size: 15px !important;
                font-weight: 600 !important;
            }
            @media (max-width: 600px) {
                .order-detail-container { padding: 20px; }
                .od-title { font-size: 22px; }
            }
        </style>

        <div class="order-detail-container">

            <!-- Header -->
            <div class="od-header">
                <div>
                    <h2 class="od-title">${t("order_details_comanda")} #${order.id}</h2>
                    <div class="od-date">${new Date(order.createdAt).toLocaleDateString("ro-RO", { day: "2-digit", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" })}</div>
                </div>
            </div>

            <!-- Produse -->
            <div class="od-section">
                <div class="od-section-title">${t("order_details_produse_comandate")}</div>
                ${productsHtml}
            </div>

            <!-- Total -->
            <div class="od-section">
                <div class="od-section-title">Sumar plată</div>
                <div style="background:#fafafa;border:2px solid #e5e5e5;border-radius:12px;padding:20px;">
                    <div class="od-total-row">
                        <span>Subtotal</span>
                        <span>${(parseFloat(total) - 25).toFixed(2)} RON</span>
                    </div>
                    <div class="od-total-row">
                        <span>Transport</span>
                        <span>25.00 RON</span>
                    </div>
                    <div class="od-total-final">
                        <span>Total</span>
                        <span>${total} RON</span>
                    </div>
                </div>
            </div>

            <!-- Date client -->
            <div class="od-section">
                <div class="od-section-title">${isPF ? t("order_details_date_personale") : t("order_details_date_firma")}</div>
                <div class="od-info-grid">
                    ${
					isPF
						? `
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_nume_complet")}</div><div class="od-info-value">${order.pf_prenume} ${order.pf_nume_familie}</div></div>
                        <div class="od-info-card"><div class="od-info-label">Email</div><div class="od-info-value">${order.pf_email}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_telefon")}</div><div class="od-info-value">${order.pf_numar_telefon}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_adresa")}</div><div class="od-info-value">${order.pf_adresa}, ${order.pf_judet_oras}, ${order.pf_tara}</div></div>
                        ${order.pf_mentiuni ? `<div class="od-info-card"><div class="od-info-label">${t("order_details_mentiuni")}</div><div class="od-info-value">${order.pf_mentiuni}</div></div>` : ""}
                    `
						: `
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_firma")}</div><div class="od-info-value">${order.pj_nume_firma}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_cui")}</div><div class="od-info-value">${order.pj_cui}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_nr_reg")}</div><div class="od-info-value">${order.pj_nr_reg}</div></div>
                        <div class="od-info-card"><div class="od-info-label">Email</div><div class="od-info-value">${order.pj_email}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_telefon")}</div><div class="od-info-value">${order.pj_numar_telefon}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_adresa")}</div><div class="od-info-value">${order.pj_adresa}, ${order.pj_localitate}, ${order.pj_judet}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_adresa_livrare")}</div><div class="od-info-value">${order.pj_adresa_livrare}</div></div>
                        <div class="od-info-card"><div class="od-info-label">${t("order_details_banca_iban")}</div><div class="od-info-value">${order.pj_banca} — ${order.pj_iban}</div></div>
                        ${order.pj_mentiuni ? `<div class="od-info-card"><div class="od-info-label">${t("order_details_mentiuni")}</div><div class="od-info-value">${order.pj_mentiuni}</div></div>` : ""}
                    `
				}
                </div>
            </div>

            <!-- Livrare -->
            <div class="od-section">
                <div class="od-section-title">${t("order_details_livrare")}</div>
                <div class="od-info-grid">
                    <div class="od-info-card"><div class="od-info-label">${t("order_details_curier")}</div><div class="od-info-value">${order.awb || "Cargus"}</div></div>
                    <div class="od-info-card"><div class="od-info-label">${t("order_details_nr_awb")}</div><div class="od-info-value">${order.awbNumber || "N/A"}</div></div>
                    <div class="od-info-card"><div class="od-info-label">${t("order_details_factura")}</div><div class="od-info-value">${order.bill_series}-${order.bill_number}</div></div>
                    ${order.netopia_payment_id ? `<div class="od-info-card"><div class="od-info-label">${t("order_details_id_plata")}</div><div class="od-info-value">${order.netopia_payment_id}</div></div>` : ""}
                </div>
            </div>

        </div>
        `,
	});
}

export async function openReturnForm(order) {
	const selectedProducts = new Set();

	const items = parseItems(order.items);

	const productHtml = items
		.map(
			(item) => `
      <div
        class="return-item"
        data-id="${item.id}"
      >
        <div class="return-item-check">
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none">
            <path d="M16.6667 5L7.50004 14.1667L3.33337 10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <div class="return-item-content">
          <h4 class="return-item-name">${item.name}</h4>
          <div class="return-item-meta">
            <span class="return-item-sku">${item.sku}</span>
            <span class="return-item-price">${item.price} RON</span>
          </div>
        </div>
      </div>`,
		)
		.join("");

	const { value: formValues } = await MySwal.fire({
		title: "",
		width: "900px",
		background: "#ffffff",
		color: "#000000",
		showConfirmButton: true,
		showCancelButton: true,
		confirmButtonText: "Trimite returul",
		cancelButtonText: "Anulează",
		customClass: {
			popup: "premium-return-popup",
			confirmButton: "premium-confirm-btn",
			cancelButton: "premium-cancel-btn",
			htmlContainer: "premium-html-container",
		},
		html: `
      <style>
        .premium-return-popup {
          border-radius: 16px !important;
          padding: 0 !important;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15) !important;
        }
        
        .premium-html-container {
          margin: 0 !important;
          padding: 0 !important;
        }
        
        .return-form-container {
          text-align: left;
          max-height: 80vh;
          overflow-y: auto;
          padding: 40px;
        }
        
        .return-form-container::-webkit-scrollbar {
          width: 8px;
        }
        
        .return-form-container::-webkit-scrollbar-track {
          background: #f5f5f5;
          border-radius: 4px;
        }
        
        .return-form-container::-webkit-scrollbar-thumb {
          background: #d0d0d0;
          border-radius: 4px;
        }
        
        .return-form-container::-webkit-scrollbar-thumb:hover {
          background: #b0b0b0;
        }
        
        .return-form-header {
          margin-bottom: 40px;
          padding-bottom: 24px;
          border-bottom: 1px solid #e5e5e5;
        }
        
        .return-form-title {
          font-size: 32px;
          font-weight: 700;
          margin: 0 0 8px 0;
          color: #000000;
        }
        
        .return-form-subtitle {
          font-size: 15px;
          color: #666666;
          margin: 0;
        }
        
        .return-section {
          margin-bottom: 32px;
        }
        
        .section-header {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 16px;
        }
        
        .section-number {
          width: 32px;
          height: 32px;
          background: #000000;
          color: #ffffff;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 16px;
          flex-shrink: 0;
        }
        
        .section-title {
          font-size: 20px;
          font-weight: 600;
          margin: 0;
          color: #000000;
        }
        
        .section-description {
          font-size: 14px;
          color: #666666;
          margin: 8px 0 0 44px;
        }
        
        .product-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
          gap: 12px;
          margin-top: 16px;
        }
        
        .return-item {
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 12px;
          padding: 16px;
          cursor: pointer;
          transition: all 0.2s ease;
          position: relative;
          display: flex;
          align-items: flex-start;
          gap: 12px;
        }
        
        .return-item:hover {
          border-color: #d0d0d0;
          background: #f5f5f5;
        }
        
        .return-item.selected {
          border-color: #000000;
          background: #f5f5f5;
        }
        
        .return-item-check {
          width: 20px;
          height: 20px;
          border: 2px solid #d0d0d0;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #ffffff;
          background: transparent;
          transition: all 0.2s ease;
          flex-shrink: 0;
          margin-top: 2px;
        }
        
        .return-item-check svg {
          opacity: 0;
          transform: scale(0.5);
          transition: all 0.2s ease;
        }
        
        .return-item.selected .return-item-check {
          background: #000000;
          border-color: #000000;
        }
        
        .return-item.selected .return-item-check svg {
          opacity: 1;
          transform: scale(1);
        }
        
        .return-item-content {
          flex: 1;
          min-width: 0;
        }
        
        .return-item-name {
          font-size: 15px;
          font-weight: 600;
          margin: 0 0 8px 0;
          color: #000000;
          line-height: 1.3;
        }
        
        .return-item-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;
        }
        
        .return-item-sku {
          font-size: 13px;
          color: #666666;
        }
        
        .return-item-price {
          font-size: 15px;
          font-weight: 700;
          color: #000000;
        }
        
        .form-group {
          margin-bottom: 20px;
        }
        
        .form-label {
          display: block;
          font-size: 14px;
          font-weight: 600;
          color: #000000;
          margin-bottom: 8px;
        }
        
        .form-select,
        .form-textarea,
        .form-input {
          width: 100%;
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 10px;
          padding: 14px 16px;
          font-size: 15px;
          color: #000000;
          transition: all 0.2s ease;
          font-family: inherit;
        }
        
        .form-select:focus,
        .form-textarea:focus,
        .form-input:focus {
          outline: none;
          border-color: #000000;
          background: #ffffff;
        }
        
        .form-select {
          cursor: pointer;
          appearance: none;
          background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1.5L6 6.5L11 1.5' stroke='%23666666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
          background-repeat: no-repeat;
          background-position: right 16px center;
          padding-right: 44px;
        }
        
        .form-select option {
          background: #ffffff;
          color: #000000;
        }
        
        .form-textarea {
          min-height: 100px;
          resize: vertical;
        }
        
        .form-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 16px;
        }
        
        .bank-info-section {
          display: none;
          margin-top: 16px;
          padding: 20px;
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 12px;
        }
        
        .bank-info-section.visible {
          display: block;
        }
        
        .bank-info-title {
          font-size: 15px;
          font-weight: 600;
          color: #000000;
          margin: 0 0 16px 0;
        }
        
        .confirmation-section {
          margin-top: 32px;
          padding: 24px;
          background: #fafafa;
          border: 2px solid #e5e5e5;
          border-radius: 12px;
        }
        
        .confirmation-label {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          cursor: pointer;
          user-select: none;
        }
        
        .confirmation-checkbox {
          width: 20px;
          height: 20px;
          border: 2px solid #d0d0d0;
          border-radius: 6px;
          flex-shrink: 0;
          margin-top: 2px;
          cursor: pointer;
          accent-color: #000000;
        }
        
        .confirmation-text {
          font-size: 14px;
          color: #333333;
          line-height: 1.5;
        }
        
        .premium-confirm-btn {
          background: #000000 !important;
          color: #ffffff !important;
          border: none !important;
          border-radius: 10px !important;
          padding: 14px 32px !important;
          font-size: 15px !important;
          font-weight: 600 !important;
          transition: all 0.2s ease !important;
        }
        
        .premium-confirm-btn:hover {
          background: #333333 !important;
          transform: translateY(-1px);
        }
        
        .premium-cancel-btn {
          background: transparent !important;
          color: #666666 !important;
          border: 2px solid #d0d0d0 !important;
          border-radius: 10px !important;
          padding: 14px 32px !important;
          font-size: 15px !important;
          font-weight: 600 !important;
          transition: all 0.2s ease !important;
        }
        
        .premium-cancel-btn:hover {
          border-color: #b0b0b0 !important;
          color: #333333 !important;
        }
        
        @media (max-width: 768px) {
          .return-form-container {
            padding: 24px;
          }
          
          .return-form-title {
            font-size: 24px;
          }
          
          .product-grid {
            grid-template-columns: 1fr;
          }
          
          .form-grid {
            grid-template-columns: 1fr;
          }
          
          .section-title {
            font-size: 18px;
          }
        }
      </style>
      
      <div class="return-form-container">
        <div class="return-form-header">
          <h2 class="return-form-title">Formular de retur</h2>
          <p class="return-form-subtitle">Completează formularul pentru a iniția procesul de returnare</p>
        </div>
        
        <div class="return-section">
          <div class="section-header">
            <div class="section-number">1</div>
            <h3 class="section-title">Selectează produsele</h3>
          </div>
          <p class="section-description">Alege produsele pe care dorești să le returnezi din comanda ta</p>
          <div class="product-grid" id="product-list">${productHtml}</div>
        </div>
        
        <div class="return-section">
          <div class="section-header">
            <div class="section-number">2</div>
            <h3 class="section-title">Motivul returului</h3>
          </div>
          <div class="form-group">
            <label class="form-label" for="reason">Selectează motivul principal</label>
            <select id="reason" class="form-select">
              <option value="">Alege un motiv...</option>
              <option value="defect">Produs defect / neconform</option>
              <option value="gresit">Produs greșit livrat</option>
              <option value="descriere">Nu corespunde descrierii</option>
              <option value="marime">Mărime nepotrivită</option>
              <option value="renuntare">Renunțare la cumpărare</option>
              <option value="garantie">Trimis pentru garantie</option>
              <option value="altul">Alt motiv</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label" for="details">Detalii suplimentare (opțional)</label>
            <textarea id="details" class="form-textarea" placeholder="Descrie problema sau motivul returului..."></textarea>
          </div>
        </div>
        
        <div class="return-section">
          <div class="section-header">
            <div class="section-number">3</div>
            <h3 class="section-title">Metoda de rambursare</h3>
          </div>
          <div class="form-group">
            <label class="form-label" for="refundMethod">Cum dorești să primești banii înapoi?</label>
            <select id="refundMethod" class="form-select">
              <option value="cont">Transfer bancar</option>

            </select>
          </div>
          
          <div id="bankInfo" class="bank-info-section visible">
            <h4 class="bank-info-title">Detalii cont bancar</h4>
            <div class="form-grid">
              <div class="form-group">
                <label class="form-label" for="iban">IBAN</label>
                <input id="iban" class="form-input" placeholder="RO49 AAAA 1B31 0075 9384 0000" />
              </div>
              <div class="form-group">
                <label class="form-label" for="accountName">Titular cont</label>
                <input id="accountName" class="form-input" placeholder="Nume complet" />
              </div>
              <div class="form-group">
                <label class="form-label" for="bankName">Banca</label>
                <input id="bankName" class="form-input" placeholder="Numele băncii" />
              </div>
            </div>
          </div>
        </div>
        
        <div class="return-section">
          <div class="section-header">
            <div class="section-number">4</div>
            <h3 class="section-title">Modalitate de retur</h3>
          </div>
          <div class="form-group">
            <label class="form-label" for="returnMethod">Cum vrei să returnezi produsul?</label>
            <select id="returnMethod" class="form-select">
              <option value="ridicare">Ridicare de la domiciliu</option>
              <option value="locker">Depunere în locker / easybox </option>
              <option value="propriu">Expediere prin curier</option>
            </select>
          </div>
        </div>
        
        <div class="confirmation-section">
          <label class="confirmation-label">
            <input type="checkbox" id="confirm" class="confirmation-checkbox" />
            <span class="confirmation-text">
              Confirm că datele introduse sunt corecte și doresc returnarea produsului. Am citit și sunt de acord cu politica de returnare.
            </span>
          </label>
        </div>
      </div>
    `,
		preConfirm: () => {
			const reason = document.getElementById("reason").value;
			const details = document.getElementById("details").value;
			const refundMethod = document.getElementById("refundMethod").value;
			const iban = document.getElementById("iban").value;
			const accountName = document.getElementById("accountName").value;
			const bankName = document.getElementById("bankName").value;
			const returnMethod = document.getElementById("returnMethod").value;
			const confirm = document.getElementById("confirm").checked;

			if (selectedProducts.size === 0) return Swal.showValidationMessage("Selectează cel puțin un produs.");
			if (!reason) return Swal.showValidationMessage("Alege motivul returului.");
			if (!confirm) return Swal.showValidationMessage("Trebuie să confirmi declarația.");

			return {
				selectedItems: Array.from(selectedProducts),
				reason,
				details,
				refundMethod,
				iban,
				accountName,
				bankName,
				returnMethod,
				createdAt: new Date().toISOString(),
			};
		},
		didOpen: () => {
			// Product selection
			document.querySelectorAll(".return-item").forEach((el) => {
				el.addEventListener("click", () => {
					const id = parseInt(el.dataset.id);
					if (selectedProducts.has(id)) {
						selectedProducts.delete(id);
						el.classList.remove("selected");
					} else {
						selectedProducts.add(id);
						el.classList.add("selected");
					}
				});
			});
		},
	});

	if (formValues) {
		const orderName =
			order.pf_prenume.length >= 1
				? order.pf_nume_familie || order.pf_prenume || "Client"
				: order.pj_nume_firma || "Client Firma";
		const orderEmail = order.pf_prenume.length >= 1 ? order.pf_email : order.pj_email;
		const orderPhone = order.pf_prenume.length >= 1 ? order.pf_numar_telefon : order.pj_numar_telefon;

		const returnData = {
			orderID: order.id,
			customer: {
				name: orderName || "",
				email: orderEmail || "",
				phone: orderPhone || "",
			},
			...formValues,
		};

		const returnResponse = await fetchWrapper.post("/api/users/returns", returnData);

		if (returnResponse.success === true) {
			Swal.fire({
				title: "Trimis!",
				text: "Cererea de retur a fost înregistrată cu succes.",
				icon: "success",
				background: "#ffffff",
				color: "#000000",
				confirmButtonColor: "#000000",
				customClass: {
					confirmButton: "premium-confirm-btn",
				},
			});
		} else {
			Swal.fire({
				title: "Eroare",
				text:
					returnResponse.error ||
					"A apărut o eroare la trimiterea cererii de retur. Te rugăm să încerci din nou.",
				icon: "error",
				background: "#ffffff",
				color: "#000000",
				confirmButtonColor: "#000000",
				customClass: {
					confirmButton: "premium-confirm-btn",
				},
			});
		}

		return returnData;
	}
}

export default function Orders() {
	const [orderData, setOrderData] = useState([]);

     const { t } = useT(); 

	const fetchUserOrders = async () => {
		try {
			const data = await fetchWrapper.get("/api/users/getorders");
			setOrderData(data[0].userOrders);
		} catch (error) {
			console.error("Error fetching user orders:", error);
		}
	};

	useEffect(() => {
		fetchUserOrders();
	}, []);

	const viewOrderDetails = (order) => {
		window.open(order.bill, "_blank");
	};

	const viewAWB = (order) => {
		window.open(order.awbUrl, "_blank");
	};

	const viewInstructions = async (instructionsUrl) => {
		window.open(instructionsUrl, "_blank");
	};

	const viewCertificate = async (certificateUrl) => {
		if (certificateUrl) {
			window.open(certificateUrl, "_blank");
		}
	};

	return (
		<div className='my-account-content account-order'>
			<div className='wrap-account-order'>
				<table>
					<thead>
						<tr>
							<th className='fw-6'>{t("contul_meu_orders_comanda")}</th>
							<th className='fw-6'>Data</th>
							<th className='fw-6'>Status</th>
							<th className='fw-6'>Total</th>
							<th className='fw-6'>{t("contul_meu_actiuni")}</th>
						</tr>
					</thead>
					<tbody>
						{orderData.length > 0 ? (
							orderData.map((order) => (
								<tr key={order.id}>
									<td className='order-number'>#{order.id}</td>
									<td className='order-date'>
										{new Date(order.createdAt).toLocaleDateString("ro-RO")}
									</td>
									<td className='order-status'>{order.status}</td>
									<td className='order-total'>
										{(() => {
											const items =
												typeof order.items === "string"
													? JSON.parse(order.items)
													: order.items;

											return (
												(Array.isArray(items)
													? items.reduce(
															(sum, item) =>
																sum + item.price * item.quantity,
															0,
														)
													: 0) + 25
											).toFixed(2);
										})()}
										RON
									</td>
									<td className='order-actions'>
										<button
											className='btn btn-primary'
											style={{
												marginRight: 10,
												borderRadius: 50,
												backgroundColor: "black",
												color: "white",
												border: "1px solid black",
												marginBottom: 10,
											}}
											onClick={() => openOrderDetails(order, t)}>
											<Info /> {t("contul_meu_order_details")}
										</button>
										<button
											className='btn btn-primary'
											style={{
												marginRight: 10,
												borderRadius: 50,
												backgroundColor: "white",
												color: "black",
												border: "1px solid black",
												marginBottom: 10,
											}}
											onClick={() => viewOrderDetails(order)}>
											<Newspaper /> {t("contul_meu_order_factura")}
										</button>

										<button
											className='btn btn-primary'
											style={{
												marginRight: 10,
												borderRadius: 50,
												backgroundColor: "white",
												color: "black",
												border: "1px solid black",
												marginBottom: 10,
											}}
											onClick={() => viewAWB(order)}>
											<Box /> {t("contul_meu_order_awb")}
										</button>

										<button
											className='btn btn-primary'
											style={{
												marginRight: 10,
												borderRadius: 50,
												backgroundColor: "white",
												color: "black",
												border: "1px solid black",
												marginBottom: 10,
											}}
											onClick={() => viewCertificate(order.certificate)}>
											<Newspaper /> {t("contul_meu_cert_garantie")}
										</button>

										<button
											className='btn btn-primary'
											style={{
												marginRight: 10,
												borderRadius: 50,
												backgroundColor: "white",
												color: "black",
												border: "1px solid black",
												marginBottom: 10,
											}}
											onClick={() => viewInstructions(order.informations)}>
											<Info /> {t("contul_meu_instructiuni")}
										</button>

										<button
											className='btn btn-primary'
											onClick={() => openConformitateForm(order)}
											style={{
												marginRight: 10,
												marginBottom: 10,
												borderRadius: 50,
												backgroundColor: "white",
												color: "black",
												border: "1px solid black",
											}}>
											<ShieldCheck /> {t("contul_meu_cert_conformitate")}{" "}
										</button>

										{order.status === "paid" &&
											(() => {
												const diffDays = Math.floor(
													(new Date() - new Date(order.createdAt)) /
														(1000 * 60 * 60 * 24),
												);

												if (diffDays <= 30) {
													const daysLeft = 30 - diffDays;

													return (
														<button
															className='btn btn-primary'
															onClick={() => openReturnForm(order)}
															style={{
																marginRight: 10,
																borderRadius: 50,
																backgroundColor: "white",
																color: "black",
																border: "1px solid black",
															}}>
															<CalendarSync /> {t("contul_meu_formular_retur")}{" "}
															<b>({daysLeft} {t("contul_meu_zile_ramase")})</b>
														</button>
													);
												}

												return null;
											})()}
									</td>
								</tr>
							))
						) : (
							<tr>
								<td colSpan='5' className='text-center'>
									Nicio comanda înregistrată.
								</td>
							</tr>
						)}
					</tbody>
				</table>
			</div>
		</div>
	);
}
