﻿"use client";

import React, { useState, useMemo, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { HOUSE_PLANS_DATA, HousePlan } from "@/data/portalData";
import { 
  Layers, 
  Bed, 
  Maximize2, 
  Download, 
  CheckCircle2, 
  Sparkles, 
  SlidersHorizontal, 
  Compass, 
  Building,
  RotateCcw,
  X,
  FileCheck
} from "lucide-react";

function HousePlansContent() {
  const searchParams = useSearchParams();
  const initialPlanSlug = searchParams.get("plan");

  const [selectedStyle, setSelectedStyle] = useState("All");
  const [selectedPerchRange, setSelectedPerchRange] = useState("All");
  const [selectedBedrooms, setSelectedBedrooms] = useState(0);

  // Blueprint Request Modal
  const [activePlanModal, setActivePlanModal] = useState<HousePlan | null>(
    HOUSE_PLANS_DATA.find((p) => p.slug === initialPlanSlug) || null
  );
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [landPerches, setLandPerches] = useState("10");
  const [landLocation, setLandLocation] = useState("Colombo Suburbs");
  const [requestSuccess, setRequestSuccess] = useState(false);

  const filteredPlans = useMemo(() => {
    return HOUSE_PLANS_DATA.filter((plan) => {
      if (selectedStyle !== "All" && plan.style !== selectedStyle) return false;
      if (selectedPerchRange === "small" && plan.maxPerch > 10) return false;
      if (selectedPerchRange === "medium" && (plan.minPerch > 15 || plan.maxPerch < 10)) return false;
      if (selectedPerchRange === "large" && plan.maxPerch < 16) return false;
      if (selectedBedrooms > 0 && plan.bedrooms < selectedBedrooms) return false;
      return true;
    });
  }, [selectedStyle, selectedPerchRange, selectedBedrooms]);

  const handleSubmitRequest = (e: React.FormEvent) => {
    e.preventDefault();
    setRequestSuccess(true);
  };

  const handleCloseModal = () => {
    setActivePlanModal(null);
    setRequestSuccess(false);
  };

  return (
    <div className="min-h-screen py-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      
      {/* Page Header */}
      <div className="mb-10 text-center max-w-3xl mx-auto space-y-4">
        <div className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-extrabold bg-[#ecfdf5] text-[#059669]">
          <Layers className="w-3.5 h-3.5" /> SLIA Accredited Architectural Catalog
        </div>
        <h1 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight font-display-lg">
          Architectural House Plans & Blueprints
        </h1>
        <p className="text-slate-500 text-sm sm:text-base leading-relaxed">
          Pre-designed, climate-responsive tropical luxury home blueprints. Each package includes structural drawings, MEP engineering schematics, 3D photorealistic renderings, and certified BOQ estimates.
        </p>
      </div>

      {/* Filter Bar */}
      <div className="bg-[#0e0e10] rounded-3xl border border-[#FFE259]/25 text-white p-6 border border-zinc-800 shadow-sm mb-10">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          
          {/* Style */}
          <div>
            <label className="block text-xs font-bold text-slate-300 uppercase tracking-wider mb-2">
              Architectural Style
            </label>
            <select
              value={selectedStyle}
              onChange={(e) => setSelectedStyle(e.target.value)}
              className="w-full bg-[#18181b] border border-zinc-700 rounded-2xl px-3.5 py-2.5 text-xs font-bold text-slate-200 focus:outline-none focus:border-[#FFE259]"
            >
              <option value="All">All Architectural Styles</option>
              <option value="Tropical Modern">Tropical Modern</option>
              <option value="Dutch Colonial Revival">Dutch Colonial Revival</option>
              <option value="Contemporary Minimalist">Contemporary Minimalist</option>
            </select>
          </div>

          {/* Land Perches */}
          <div>
            <label className="block text-xs font-bold text-slate-300 uppercase tracking-wider mb-2">
              Land Extent (Perches)
            </label>
            <select
              value={selectedPerchRange}
              onChange={(e) => setSelectedPerchRange(e.target.value)}
              className="w-full bg-[#18181b] border border-zinc-700 rounded-2xl px-3.5 py-2.5 text-xs font-bold text-slate-200 focus:outline-none focus:border-[#FFE259]"
            >
              <option value="All">Any Perch Size</option>
              <option value="small">6 - 10 Perches (Compact Urban)</option>
              <option value="medium">10 - 15 Perches (Suburban Prime)</option>
              <option value="large">15 - 25+ Perches (Sprawling Estate)</option>
            </select>
          </div>

          {/* Bedrooms */}
          <div>
            <label className="block text-xs font-bold text-slate-300 uppercase tracking-wider mb-2">
              Bedrooms
            </label>
            <select
              value={selectedBedrooms}
              onChange={(e) => setSelectedBedrooms(Number(e.target.value))}
              className="w-full bg-[#18181b] border border-zinc-700 rounded-2xl px-3.5 py-2.5 text-xs font-bold text-slate-200 focus:outline-none focus:border-[#FFE259]"
            >
              <option value={0}>Any Bedrooms</option>
              <option value={3}>3+ Bedrooms</option>
              <option value={4}>4+ Bedrooms</option>
              <option value={5}>5+ Bedrooms</option>
            </select>
          </div>

          {/* Reset Filters */}
          <div className="flex items-end">
            <button
              onClick={() => {
                setSelectedStyle("All");
                setSelectedPerchRange("All");
                setSelectedBedrooms(0);
              }}
              className="w-full py-2.5 rounded-2xl border border-zinc-700 hover:border-[#059669] text-slate-600 hover:text-[#059669] text-xs font-bold transition-colors flex items-center justify-center gap-1.5"
            >
              <RotateCcw className="w-3.5 h-3.5" />
              <span>Reset Filters</span>
            </button>
          </div>

        </div>
      </div>

      {/* House Plans Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {filteredPlans.map((plan) => (
          <div
            key={plan.id}
            className="bg-[#0e0e10] rounded-3xl border border-[#FFE259]/25 text-white overflow-hidden border border-zinc-800 shadow-[0px_10px_30px_rgba(15,16,38,0.05)] hover:shadow-xl transition-all flex flex-col justify-between"
          >
            <div>
              {/* Image & Style Tag */}
              <div className="relative aspect-[16/10] overflow-hidden bg-[#18181b]">
                <img
                  src={plan.heroImage}
                  alt={plan.name}
                  className="w-full h-full object-cover hover:scale-105 transition-transform duration-500"
                />
                <div className="absolute top-3 left-3 px-3 py-1 rounded-full text-xs font-extrabold bg-[#059669] text-white shadow-md">
                  {plan.style}
                </div>
                <div className="absolute bottom-3 left-3 right-3 bg-black/70 backdrop-blur-md rounded-2xl p-2.5 text-white flex justify-between text-xs font-semibold">
                  <span>Plot: {plan.minPerch} - {plan.maxPerch} Perches</span>
                  <span>{plan.totalSqft} SqFt</span>
                </div>
              </div>

              {/* Plan Specs */}
              <div className="p-6 space-y-4">
                <div>
                  <h3 className="text-xl font-bold text-white font-display-lg">{plan.name}</h3>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2 leading-relaxed">
                    {plan.description}
                  </p>
                </div>

                <div className="grid grid-cols-3 gap-2 p-3 bg-[#18181b] rounded-2xl border border-zinc-800 text-slate-300 text-center text-xs font-bold text-slate-300">
                  <div>
                    <span className="text-[#059669] block text-base font-extrabold">{plan.bedrooms}</span>
                    <span className="text-[10px] text-slate-400 font-medium">Beds</span>
                  </div>
                  <div className="border-l border-zinc-700">
                    <span className="text-[#059669] block text-base font-extrabold">{plan.bathrooms}</span>
                    <span className="text-[10px] text-slate-400 font-medium">Baths</span>
                  </div>
                  <div className="border-l border-zinc-700">
                    <span className="text-[#059669] block text-base font-extrabold">{plan.floors}</span>
                    <span className="text-[10px] text-slate-400 font-medium">Floors</span>
                  </div>
                </div>

                <div className="p-3 bg-[#ecfdf5]/30 rounded-2xl border border-[#059669]/20 text-xs">
                  <div className="flex justify-between font-bold text-slate-200">
                    <span>Est. Turnkey BOQ:</span>
                    <span className="text-[#059669] font-extrabold">LKR {plan.estimatedBOQLKR}</span>
                  </div>
                  
                </div>

                <div className="space-y-1.5">
                  <span className="text-[11px] font-bold text-slate-300 uppercase tracking-wider block">Key Features:</span>
                  {plan.features.slice(0, 3).map((f, idx) => (
                    <div key={idx} className="flex items-center gap-1.5 text-xs text-slate-600">
                      <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
                      <span className="truncate">{f}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* CTA Button */}
            <div className="px-6 pb-6 pt-2">
              <button
                onClick={() => setActivePlanModal(plan)}
                className="w-full bg-[#0e0e10] border border-[#FFE259]/25 hover:bg-[#059669] text-white text-xs font-bold py-3.5 rounded-full text-center transition-colors shadow-md flex items-center justify-center gap-2"
              >
                <Download className="w-4 h-4" />
                <span>View Full Blueprints & Request CAD</span>
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Blueprint Detail & Request Modal */}
      {activePlanModal && (
        <div className="fixed inset-0 z-50 overflow-y-auto bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-[#0e0e10] rounded-3xl border border-[#FFE259]/25 text-white max-w-2xl w-full overflow-hidden shadow-2xl border border-zinc-800 relative animate-in fade-in zoom-in-95">
            
            <button
              onClick={handleCloseModal}
              className="absolute top-4 right-4 z-10 w-9 h-9 rounded-full bg-[#18181b] hover:bg-zinc-800 text-slate-300 flex items-center justify-center"
            >
              <X className="w-5 h-5" />
            </button>

            {requestSuccess ? (
              <div className="p-8 text-center space-y-4">
                <div className="w-16 h-16 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center mx-auto">
                  <FileCheck className="w-8 h-8" />
                </div>
                <h3 className="text-xl font-bold text-white font-display-lg">
                  Architectural Drawing Package Requested!
                </h3>
                <p className="text-xs text-slate-600 max-w-md mx-auto">
                  Our chief chartered architect will review your land location (<strong>{landLocation}</strong>) and contact you within 24 hours with custom adaptation advice and complete CAD schematics for <strong>{activePlanModal.name}</strong>.
                </p>
                <button
                  onClick={handleCloseModal}
                  className="bg-[#059669] text-white font-bold text-xs px-8 py-3 rounded-full shadow-md"
                >
                  Done
                </button>
              </div>
            ) : (
              <div className="p-6 sm:p-8 space-y-6">
                <div>
                  <span className="text-[11px] font-bold uppercase tracking-widest text-[#059669]">
                    Architectural Blueprint Specification
                  </span>
                  <h3 className="text-xl font-bold text-white font-display-lg">
                    {activePlanModal.name}
                  </h3>
                  <p className="text-xs text-slate-500 mt-1">
                    {activePlanModal.style} • {activePlanModal.totalSqft} SqFt • {activePlanModal.bedrooms} Beds • {activePlanModal.bathrooms} Baths
                  </p>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="rounded-2xl overflow-hidden border border-zinc-700 bg-[#18181b] p-2">
                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1">
                      2D Architectural Floor Layout
                    </span>
                    <img
                      src={activePlanModal.floorPlan2D}
                      alt="Floor Plan"
                      className="w-full h-40 object-contain rounded-xl"
                    />
                  </div>
                  <div className="rounded-2xl overflow-hidden border border-zinc-700 bg-[#18181b] p-2">
                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1">
                      3D Photorealistic Exterior Render
                    </span>
                    <img
                      src={activePlanModal.rendering3D}
                      alt="3D Render"
                      className="w-full h-40 object-cover rounded-xl"
                    />
                  </div>
                </div>

                {/* Form */}
                <form onSubmit={handleSubmitRequest} className="space-y-3 pt-2">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <input
                      type="text"
                      required
                      placeholder="Your Full Name"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs focus:outline-none focus:border-[#FFE259]"
                    />
                    <input
                      type="email"
                      required
                      placeholder="Email Address"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs focus:outline-none focus:border-[#FFE259]"
                    />
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <input
                      type="text"
                      placeholder="Your Land Size in Perches (e.g. 12P)"
                      value={landPerches}
                      onChange={(e) => setLandPerches(e.target.value)}
                      className="bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs focus:outline-none focus:border-[#FFE259]"
                    />
                    <input
                      type="text"
                      placeholder="Land Location / City (e.g. Kaduwela, Galle)"
                      value={landLocation}
                      onChange={(e) => setLandLocation(e.target.value)}
                      className="bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs focus:outline-none focus:border-[#FFE259]"
                    />
                  </div>

                  <button
                    type="submit"
                    className="w-full bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs uppercase tracking-wider py-3.5 rounded-full shadow-lg shadow-[#059669]/20 transition-all mt-2"
                  >
                    Request Full CAD Blueprints & Customization Quote
                  </button>
                </form>
              </div>
            )}

          </div>
        </div>
      )}

    </div>
  );
}

export default function HousePlansPage() {
  return (
    <Suspense fallback={<div className="p-12 text-center text-slate-500">Loading House Plans...</div>}>
      <HousePlansContent />
    </Suspense>
  );
}