"use client";

import { useState } from "react";
import { Card } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { useRouter } from "next/navigation";
import * as XLSX from "xlsx";
import { FileUp, Users, LogIn, UserPlus, User, ShoppingCart } from "lucide-react";
import { signIn } from "next-auth/react";
import { useCart } from "@/store/useCart";

export default function CheckoutForm({ course, user, settings }: { course: any, user: any, settings: any }) {
  const router = useRouter();
  const [authMode, setAuthMode] = useState<"guest" | "login" | "register">(user ? "guest" : "login");
  const [loginPassword, setLoginPassword] = useState("");
  const [registerPassword, setRegisterPassword] = useState("");
  const [isAuthLoading, setIsAuthLoading] = useState(false);

  const { items } = useCart();
  const cartCourse = items[0] ? { id: items[0].id, title: items[0].title, price: items[0].price, thumbnail: items[0].thumbnail } : null;
  const activeCourse = course || cartCourse;

  const [isB2B, setIsB2B] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState(() => {
    if (settings?.enableStripe) return "card";
    if (settings?.enablePayPal) return "paypal";
    if (settings?.enableBTPay) return "btpay";
    if (settings?.enableBankTransfer) return "bank_transfer";
    return "card";
  });
  const [isLoading, setIsLoading] = useState(false);

  // Form states
  const [firstName, setFirstName] = useState(user?.name?.split(" ")[0] || "");
  const [lastName, setLastName] = useState(user?.name?.split(" ").slice(1).join(" ") || "");
  const [email, setEmail] = useState(user?.email || "");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  
  // B2B states
  const [companyName, setCompanyName] = useState("");
  const [cui, setCui] = useState("");
  const [regCom, setRegCom] = useState("");
  const [isFetchingANAF, setIsFetchingANAF] = useState(false);
  const [anafSuccess, setAnafSuccess] = useState(false);
  
  // Corporate Mass Upload States
  const [employeesCount, setEmployeesCount] = useState(1);
  const [fileName, setFileName] = useState("");
  const [employeeData, setEmployeeData] = useState<any[]>([]);

  // Compute dynamic price
  const activePrice = isB2B ? ((activeCourse?.price || 0) * employeesCount) : (activeCourse?.price || 0);

  const fetchANAF = async () => {
    if (!cui || cui.length < 5) return;
    setIsFetchingANAF(true);
    try {
      const res = await fetch(`/api/anaf?cui=${cui}`);
      const data = await res.json();
      if (res.ok) {
        setCompanyName(data.nume);
        setRegCom(data.regCom);
        if (data.adresa) setAddress(data.adresa);
        setAnafSuccess(true);
      } else {
        alert(data.error || "Eroare ANAF");
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsFetchingANAF(false);
    }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setFileName(file.name);
    const reader = new FileReader();
    reader.onload = (evt) => {
      try {
        const bstr = evt.target?.result;
        const wb = XLSX.read(bstr, { type: "binary" });
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        const data = XLSX.utils.sheet_to_json(ws);
        
        // Count valid rows
        if (data.length > 0) {
          setEmployeesCount(data.length);
          setEmployeeData(data);
        } else {
          alert("Fișierul XLSX este gol.");
          setEmployeesCount(1);
          setEmployeeData([]);
        }
      } catch (err) {
        console.error("XLSX parsing error:", err);
        alert("Eroare la procesarea fișierului XLSX. Asigură-te că e un format valid.");
      }
    };
    reader.readAsBinaryString(file);
  };

  const handleInlineLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsAuthLoading(true);
    try {
      const result = await signIn("credentials", {
        email,
        password: loginPassword,
        redirect: false,
      });

      if (result?.error) {
        alert("Autentificare eșuată. Verifică email-ul și parola.");
      } else {
        router.refresh(); // Refresh to inject `user` prop into CheckoutForm
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsAuthLoading(false);
    }
  };

  const handleCheckout = async (e: React.FormEvent) => {
    e.preventDefault();
    if (authMode === "login") {
      return handleInlineLogin(e);
    }

    setIsLoading(true);

    try {
      // In production, this would call /api/checkout to generate a Stripe session
      // For MVP, we pass password if they are registering, or auto-generate if guest.
      const finalPassword = authMode === "register" ? registerPassword : (authMode === "guest" && !user ? Math.random().toString(36).slice(-8) : undefined);

      let res;
      if (paymentMethod === "card") {
        res = await fetch("/api/checkout/stripe", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            courseId: activeCourse?.id,
            billingInfo: {
              firstName, lastName, email, phone, address, isB2B, companyName, cui, regCom
            },
            isB2B,
            employeesCount,
            employeeData,
            totalAmount: activePrice,
            registerPassword: finalPassword,
            authMode
          }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Eroare plată Stripe");
        if (data.url) {
          window.location.href = data.url;
          return;
        }
      } else if (paymentMethod === "btpay") {
        res = await fetch("/api/checkout/btpay", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            courseId: activeCourse?.id,
            billingInfo: { firstName, lastName, email, phone, address, isB2B, companyName, cui, regCom },
            isB2B,
            employeesCount,
            employeeData,
            totalAmount: activePrice,
            registerPassword: finalPassword,
            authMode
          }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Eroare plată BT Pay");
        if (data.url) {
          window.location.href = data.url;
          return;
        }
      } else if (paymentMethod === "paypal") {
        res = await fetch("/api/checkout/paypal", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            courseId: activeCourse?.id,
            billingInfo: { firstName, lastName, email, phone, address, isB2B, companyName, cui, regCom },
            isB2B,
            employeesCount,
            employeeData,
            totalAmount: activePrice,
            registerPassword: finalPassword,
            authMode
          }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Eroare plată PayPal");
        if (data.url) {
          window.location.href = data.url;
          return;
        }
      } else {
        // Mock transfer bancar
        res = await fetch("/api/enrollments", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            courseId: activeCourse?.id,
            paymentMethod,
            billingInfo: {
              firstName, lastName, email, phone, address, isB2B, companyName, cui, regCom
            },
            employeesCount,
            employeeData,
            totalAmount: activePrice,
            registerPassword: finalPassword,
            authMode
          }),
        });

        if (!res.ok) throw new Error("A apărut o eroare la procesarea comenzii.");

        router.push("/checkout/success?op=true");
        router.refresh();
      }

    } catch (error: any) {
      console.error(error);
      alert(error.message || "Eroare la procesare plată. Te rugăm să încerci din nou.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleCheckout} className="flex flex-col lg:flex-row gap-12">
      
      {/* Left Column - Billing Details */}
      <div className="w-full lg:w-2/3 space-y-8">
        
        {/* Auth Slider for Unauthenticated Users */}
        {!user && (
          <Card className="p-2 sm:p-4 bg-white/5 backdrop-blur-xl border-white/10 flex flex-col md:flex-row items-center justify-between gap-4">
            <div className="flex p-1 bg-black/40 rounded-xl border border-white/10 w-full">
              <button 
                type="button"
                onClick={() => setAuthMode("login")}
                className={`flex-1 flex items-center justify-center gap-2 px-4 sm:px-6 py-3 rounded-lg text-xs sm:text-sm font-bold transition-all ${authMode === 'login' ? 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white shadow-[0_0_20px_rgba(6,182,212,0.4)]' : 'text-white/50 hover:text-white'}`}
              >
                <LogIn className="w-4 h-4" />
                Intră în Cont
              </button>
              <button 
                type="button"
                onClick={() => setAuthMode("register")}
                className={`flex-1 flex items-center justify-center gap-2 px-4 sm:px-6 py-3 rounded-lg text-xs sm:text-sm font-bold transition-all ${authMode === 'register' ? 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white shadow-[0_0_20px_rgba(6,182,212,0.4)]' : 'text-white/50 hover:text-white'}`}
              >
                <UserPlus className="w-4 h-4" />
                Creare Cont
              </button>
              <button 
                type="button"
                onClick={() => setAuthMode("guest")}
                className={`flex-1 flex items-center justify-center gap-2 px-4 sm:px-6 py-3 rounded-lg text-xs sm:text-sm font-bold transition-all ${authMode === 'guest' ? 'bg-white text-black shadow-lg' : 'text-white/50 hover:text-white'}`}
              >
                <User className="w-4 h-4" />
                Guest (Fără Cont)
              </button>
            </div>
          </Card>
        )}

        {authMode === "login" && !user ? (
          <Card className="p-8 bg-white/5 backdrop-blur-xl border-white/10">
            <h2 className="text-xl font-bold text-white mb-6 font-heading flex items-center gap-3">
              <LogIn className="w-6 h-6 text-cyan-400" />
              Autentificare Rapidă
            </h2>
            <div className="space-y-6">
              <Input label="Adresă de Email *" type="email" value={email} onChange={(e: any) => setEmail(e.target.value)} required />
              <Input label="Parolă *" type="password" value={loginPassword} onChange={(e: any) => setLoginPassword(e.target.value)} required />
              <Button type="submit" disabled={isAuthLoading} className="w-full h-12 bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-bold text-sm tracking-wide shadow-[0_10px_30px_rgba(6,182,212,0.3)] hover:shadow-[0_10px_40px_rgba(6,182,212,0.5)] transition-all">
                {isAuthLoading ? "SE AUTENTIFICĂ..." : "INTRĂ ÎN CONT ȘI CONTINUĂ"}
              </Button>
            </div>
          </Card>
        ) : (
          <>
            {/* Account Type Toggle */}
            <Card className="p-8 bg-white/5 backdrop-blur-xl border-white/10">
          <h2 className="text-xl font-bold text-white mb-6 font-heading">Tip Facturare</h2>
          <div className="flex p-1 bg-black/20 rounded-xl border border-white/10 w-full sm:w-fit">
            <button 
              type="button"
              onClick={() => setIsB2B(false)}
              className={`flex-1 sm:flex-none px-6 py-3 rounded-lg text-sm font-semibold transition-all ${!isB2B ? 'bg-white text-black shadow-lg scale-105' : 'text-white/50 hover:text-white'}`}
            >
              Persoană Fizică
            </button>
            <button 
              type="button"
              onClick={() => setIsB2B(true)}
              className={`flex-1 sm:flex-none px-6 py-3 rounded-lg text-sm font-semibold transition-all ${isB2B ? 'bg-white text-black shadow-lg scale-105' : 'text-white/50 hover:text-white'}`}
            >
              Companie (B2B)
            </button>
          </div>
        </Card>

        {/* Billing Details Form */}
        <Card className="p-8 bg-white/5 backdrop-blur-xl border-white/10">
          {isB2B ? (
            <div className="animate-fade-in">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-white font-heading">Detalii Companie (e-Factura)</h2>
                <div className="flex items-center gap-2">
                  {anafSuccess && <span className="px-2 py-1 bg-rima-success/10 text-rima-success text-[10px] uppercase font-bold rounded">Date validate</span>}
                  <span className="px-2 py-1 bg-rima-success/10 text-rima-success text-[10px] uppercase font-bold rounded">SPV Automat</span>
                </div>
              </div>
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                <div className="relative">
                  <Input label="CUI / CIF *" value={cui} onChange={(e: any) => { setCui(e.target.value); setAnafSuccess(false); }} placeholder="Ex: RO12345678" required={isB2B} inputClassName="pr-[110px]" />
                  <div className="absolute bottom-[2px] right-[2px]">
                    <Button type="button" onClick={fetchANAF} disabled={isFetchingANAF} className="h-[38px] px-4 text-xs font-bold rounded-lg shadow-none">
                      {isFetchingANAF ? "Se caută..." : "Caută ANAF"}
                    </Button>
                  </div>
                </div>
                <Input label="Nr. Reg. Comerțului *" value={regCom} onChange={(e: any) => setRegCom(e.target.value)} placeholder="Ex: J40/1234/2026" required={isB2B} />
              </div>

              <div className="grid grid-cols-1 gap-6 mb-6">
                <Input label="Nume Companie *" value={companyName} onChange={(e: any) => setCompanyName(e.target.value)} placeholder="SC RIMA ACADEMY SRL" required={isB2B} />
                <Input label="Adresă Sediu Social *" value={address} onChange={(e: any) => setAddress(e.target.value)} placeholder="Strada, Număr, Oraș, Județ" required />
              </div>

              <div className="mt-8 pt-8 border-t border-rima-border/50">
                <h2 className="text-xl font-bold text-white mb-6 font-heading">Date Reprezentant Legal</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                  <Input label="Prenume *" value={firstName} onChange={(e: any) => setFirstName(e.target.value)} required />
                  <Input label="Nume *" value={lastName} onChange={(e: any) => setLastName(e.target.value)} required />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                  <Input label="Adresă de Email *" type="email" value={email} onChange={(e: any) => setEmail(e.target.value)} required />
                  <Input label="Telefon *" type="tel" value={phone} onChange={(e: any) => setPhone(e.target.value)} required />
                </div>
              </div>
              
              <div className="mt-8 p-6 bg-black/40 rounded-xl border border-white/10 relative overflow-hidden group">
                <div className="absolute inset-0 bg-gradient-to-r from-cyan-500/5 to-blue-500/5 group-hover:from-cyan-500/10 group-hover:to-blue-500/10 transition-colors pointer-events-none" />
                <h3 className="text-lg font-bold text-white mb-2 font-heading flex items-center gap-2">
                  <Users className="w-5 h-5 text-cyan-400" />
                  Înrolare Angajați / Echipă
                </h3>
                <p className="text-sm text-rima-muted mb-4">
                  Încarcă un fișier Excel (.xlsx) cu datele echipei (Nume, Prenume, Email). Sistemul va calcula automat prețul pentru {activeCourse?.title} în funcție de numărul de persoane.
                </p>
                
                <div className="flex items-center gap-4">
                  <label className="relative cursor-pointer group/btn">
                    <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} className="hidden" />
                    <div className="px-5 py-3 bg-white/5 border border-white/10 hover:border-cyan-500/50 rounded-lg text-sm font-bold text-white flex items-center gap-2 transition-all">
                      <FileUp className="w-4 h-4 group-hover/btn:-translate-y-1 transition-transform" />
                      {fileName ? "Schimbă Fișierul" : "Încarcă .XLSX"}
                    </div>
                  </label>
                  
                  {employeesCount > 1 && (
                    <div className="flex items-center gap-2 text-sm font-bold text-cyan-400 bg-cyan-400/10 px-4 py-3 rounded-lg border border-cyan-400/20">
                      <Users className="w-4 h-4" />
                      <span>{employeesCount} persoane detectate</span>
                    </div>
                  )}
                </div>
              </div>

              <p className="text-xs text-rima-muted mt-6 font-medium">Factura electronică va fi emisă automat în sistemul RO e-Factura SPV la confirmarea plății.</p>
            </div>
          ) : (
            <div className="animate-fade-in">
              <h2 className="text-xl font-bold text-white mb-6 font-heading">Detalii Personale</h2>
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                <Input label="Prenume *" value={firstName} onChange={(e: any) => setFirstName(e.target.value)} required />
                <Input label="Nume *" value={lastName} onChange={(e: any) => setLastName(e.target.value)} required />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-6">
                <Input label="Adresă de Email *" type="email" value={email} onChange={(e: any) => setEmail(e.target.value)} required />
                <Input label="Telefon *" type="tel" value={phone} onChange={(e: any) => setPhone(e.target.value)} required />
              </div>

              <Input label="Adresă Completă *" value={address} onChange={(e: any) => setAddress(e.target.value)} placeholder="Strada, Număr, Oraș, Județ" required />
            </div>
          )}
        </Card>
          </>
        )}
      </div>

      {/* Right Column - Order Summary */}
      <div className="w-full lg:w-1/3">
        <Card className="p-8 sticky top-28 bg-white/5 backdrop-blur-xl border-white/10 shadow-2xl">
          <h2 className="text-xl font-bold text-white mb-6 font-heading">Sumar Comandă</h2>
          
          <div className="space-y-4 mb-6">
            <div className="flex gap-4">
              <div className="w-16 h-16 bg-rima-surface rounded-xl shrink-0 overflow-hidden relative border border-white/5">
                <div className="absolute inset-0 bg-gradient-to-tr from-rima-primary/20 to-transparent"></div>
              </div>
              <div className="flex-1">
                <h4 className="text-sm font-bold text-white leading-snug font-heading">{activeCourse?.title}</h4>
                <div className="text-[11px] font-bold uppercase tracking-wider text-rima-muted mt-1">Acces pe viață • Certificare</div>
                <div className="text-sm font-bold text-rima-primary mt-2">{activeCourse?.price} RON {isB2B && employeesCount > 1 && <span className="text-white/50 text-xs font-normal">x {employeesCount} pers.</span>}</div>
              </div>
            </div>
          </div>

          <div className="border-t border-white/10 pt-4 space-y-3 mb-8">
            <div className="flex justify-between text-sm text-white/50 font-medium">
              <span>Subtotal</span>
              <span>{activePrice} RON</span>
            </div>
            <div className="flex justify-between text-sm text-white/50 font-medium">
              <span>Taxe (TVA inclus)</span>
              <span>0 RON</span>
            </div>
            <div className="flex justify-between text-lg font-bold text-white pt-2 border-t border-white/10">
              <span>Total</span>
              <span className="text-cyan-400">{activePrice} RON</span>
            </div>
          </div>

          <h3 className="text-sm font-bold text-white mb-4 uppercase tracking-wider">Metodă de Plată</h3>
          <div className="space-y-3 mb-8">
            {settings?.enableStripe && (
              <label className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${paymentMethod === 'card' ? 'bg-white/10 border-white text-white' : 'bg-black/20 border-white/5 text-white/50 hover:border-white/10'}`}>
                <input type="radio" name="payment" value="card" checked={paymentMethod === 'card'} onChange={() => setPaymentMethod('card')} className="accent-white w-4 h-4"/>
                <div className="flex-1 text-sm font-bold">Card de credit / debit (Stripe)</div>
              </label>
            )}
            
            {settings?.enablePayPal && (
              <label className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${paymentMethod === 'paypal' ? 'bg-[#003087]/20 border-[#0070BA] text-white' : 'bg-black/20 border-white/5 text-white/50 hover:border-white/10'}`}>
                <input type="radio" name="payment" value="paypal" checked={paymentMethod === 'paypal'} onChange={() => setPaymentMethod('paypal')} className="accent-[#0070BA] w-4 h-4"/>
                <div className="flex-1 text-sm font-bold flex items-center justify-between">
                  PayPal
                  <span className="text-[10px] bg-[#0070BA] text-white px-2 py-0.5 rounded">Popular</span>
                </div>
              </label>
            )}

            {/* Default mock option for Installments (Oney/TBI) */}
            <label className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${paymentMethod === 'rate' ? 'bg-emerald-500/10 border-emerald-500 text-white' : 'bg-black/20 border-white/5 text-white/50 hover:border-white/10'}`}>
              <input type="radio" name="payment" value="rate" checked={paymentMethod === 'rate'} onChange={() => setPaymentMethod('rate')} className="accent-emerald-500 w-4 h-4"/>
              <div className="flex-1 text-sm font-bold">Plata în Rate (TBI Pay / Oney)</div>
            </label>

            {settings?.enableBTPay && (
              <label className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${paymentMethod === 'btpay' ? 'bg-[#FFDE00]/10 border-[#FFDE00] text-white' : 'bg-black/20 border-white/5 text-white/50 hover:border-white/10'}`}>
                <input type="radio" name="payment" value="btpay" checked={paymentMethod === 'btpay'} onChange={() => setPaymentMethod('btpay')} className="accent-[#FFDE00] w-4 h-4"/>
                <div className="flex-1 text-sm font-bold flex items-center justify-between">
                  Banca Transilvania (BT Pay / iPay)
                  <span className="text-[10px] bg-[#FFDE00] text-black px-2 py-0.5 rounded font-black">NOU</span>
                </div>
              </label>
            )}

            {settings?.enableBankTransfer && (
              <label className={`flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-all ${paymentMethod === 'transfer' ? 'bg-white/10 border-white text-white' : 'bg-black/20 border-white/5 text-white/50 hover:border-white/10'}`}>
                <input type="radio" name="payment" value="transfer" checked={paymentMethod === 'transfer'} onChange={() => setPaymentMethod('transfer')} className="accent-white w-4 h-4"/>
                <div className="flex-1 text-sm font-bold">Transfer Bancar (Ordin de Plată)</div>
              </label>
            )}
          </div>

          <Button type="submit" disabled={isLoading} className="w-full py-4 text-sm tracking-widest bg-white text-black hover:bg-slate-200">
            {isLoading ? "SE PROCESEAZĂ..." : "FINALIZEAZĂ PLATA SECURIZATĂ"}
          </Button>
          
          <div className="text-center mt-4 text-[11px] text-white/40 font-medium flex flex-col gap-2">
            <p>Plățile cu cardul sunt procesate securizat. Nu salvăm datele cardului tău.</p>
          </div>
        </Card>
      </div>
      
    </form>
  );
}
