"use client";

import React, { useState } from "react";
import Link from "next/link";
import { Sparkles, ArrowRight, ShieldCheck, Check } from "lucide-react";
import { ShinyButton } from "./ShinyButton";
import { useAppStore } from "@/lib/store";

interface AddonOption {
  id: string;
  name: string;
  price: number;
  days: number;
}

const PLATFORMS = [
  { id: "web_starter", name: "High-Speed SME Web (Next.js)", basePrice: 50000, days: 8 },
  { id: "web_portal", name: "Full Dynamic Portal + CMS", basePrice: 120000, days: 16 },
  { id: "mobile_app", name: "Cross-Platform Mobile App (iOS/Android)", basePrice: 300000, days: 24 },
  { id: "custom_erp", name: "Custom SaaS / Desktop POS (Electron)", basePrice: 180000, days: 20 },
];

const ADDONS: AddonOption[] = [
  { id: "fbr_tax", name: "FBR Tier-1 Tax POS Integration", price: 35000, days: 4 },
  { id: "payment_gateways", name: "Payment Gateway (JazzCash/Easypaisa/Stripe)", price: 25000, days: 3 },
  { id: "seo_boost", name: "Technical SEO & Schema Launch Pack", price: 20000, days: 2 },
  { id: "biometric_auth", name: "Biometric & Hardware Peripheral Drivers", price: 30000, days: 4 },
];

const SUPPORT_TIERS = [
  { id: "standard", name: "30 Days Standard Warranty", multiplier: 1 },
  { id: "priority", name: "90 Days Priority SLA (+PKR 25,000)", multiplier: 1, fixed: 25000 },
  { id: "dedicated", name: "6 Months Retainer SLA (+PKR 60,000)", multiplier: 1, fixed: 60000 },
];

export function QuoteCalculator() {
  const { formatPrice } = useAppStore();
  const [selectedPlatform, setSelectedPlatform] = useState(PLATFORMS[0].id);
  const [selectedAddons, setSelectedAddons] = useState<string[]>(["fbr_tax"]);
  const [selectedSupport, setSelectedSupport] = useState(SUPPORT_TIERS[0].id);
  const [isRushOrder, setIsRushOrder] = useState(false);

  const platform = PLATFORMS.find((p) => p.id === selectedPlatform) || PLATFORMS[0];
  const support = SUPPORT_TIERS.find((s) => s.id === selectedSupport) || SUPPORT_TIERS[0];

  const toggleAddon = (id: string) => {
    setSelectedAddons((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]
    );
  };

  const addonsTotal = selectedAddons.reduce((acc, addonId) => {
    const addon = ADDONS.find((a) => a.id === addonId);
    return acc + (addon ? addon.price : 0);
  }, 0);

  const addonsDays = selectedAddons.reduce((acc, addonId) => {
    const addon = ADDONS.find((a) => a.id === addonId);
    return acc + (addon ? addon.days : 0);
  }, 0);

  const baseSubtotal = platform.basePrice + addonsTotal + (support.fixed || 0);
  const rushMultiplier = isRushOrder ? 1.25 : 1.0;
  const totalPKR = Math.round(baseSubtotal * rushMultiplier);
  const estimatedDays = Math.max(
    5,
    Math.round((platform.days + addonsDays) * (isRushOrder ? 0.65 : 1.0))
  );

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 rounded-2xl border border-border bg-card p-6 sm:p-10">
      {/* Configuration Controls */}
      <div className="lg:col-span-7 space-y-6">
        {/* 1. Target Architecture */}
        <div>
          <label className="font-mono text-xs text-[#024d37] uppercase tracking-[0.12em] block mb-3">
            // 01. SELECT CORE ARCHITECTURE
          </label>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
            {PLATFORMS.map((p) => (
              <button
                key={p.id}
                onClick={() => setSelectedPlatform(p.id)}
                className={`rounded-xl border p-3.5 text-left font-mono text-xs transition-all ${
                  selectedPlatform === p.id
                    ? "border-[#024d37] bg-muted font-bold text-[#024d37] shadow-sm shadow-[#024d37]/15"
                    : "border-border bg-background text-muted-foreground hover:border-[#024d37]/50 hover:text-foreground"
                }`}
              >
                <div className="text-foreground font-sans font-semibold mb-1">{p.name}</div>
                <div className="text-[11px] text-muted-foreground">{formatPrice(p.basePrice)}</div>
              </button>
            ))}
          </div>
        </div>

        {/* 2. Technical Addons */}
        <div>
          <label className="font-mono text-xs text-[#024d37] uppercase tracking-[0.12em] block mb-3">
            // 02. MODULAR TECHNICAL ADD-ONS
          </label>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
            {ADDONS.map((addon) => {
              const isSelected = selectedAddons.includes(addon.id);
              return (
                <button
                  key={addon.id}
                  onClick={() => toggleAddon(addon.id)}
                  className={`rounded-xl border p-3.5 text-left font-mono text-xs transition-all flex items-start justify-between ${
                    isSelected
                      ? "border-[#024d37] bg-muted text-foreground font-semibold shadow-sm shadow-[#024d37]/15"
                      : "border-border bg-background text-muted-foreground hover:border-[#024d37]/40 hover:text-foreground"
                  }`}
                >
                  <div>
                    <div className="font-sans text-xs mb-0.5">{addon.name}</div>
                    <span className="text-[10px] text-muted-foreground">+{formatPrice(addon.price)}</span>
                  </div>
                  <div
                    className={`h-4 w-4 rounded border flex items-center justify-center shrink-0 mt-0.5 ${
                      isSelected
                        ? "border-[#024d37] bg-[#024d37] text-white"
                        : "border-border bg-background"
                    }`}
                  >
                    {isSelected && <Check className="h-3 w-3" />}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* 3. Delivery Speed */}
        <div>
          <label className="font-mono text-xs text-[#024d37] uppercase tracking-[0.12em] block mb-3">
            // 03. VELOCITY SPECIFICATION
          </label>
          <div className="grid grid-cols-2 gap-2.5">
            <button
              onClick={() => setIsRushOrder(false)}
              className={`rounded-xl border p-3 font-mono text-xs transition-all ${
                !isRushOrder
                  ? "border-[#024d37] bg-muted text-foreground font-bold"
                  : "border-border bg-background text-muted-foreground hover:border-[#024d37]/40"
              }`}
            >
              Standard Sprint (100% SLA)
            </button>
            <button
              onClick={() => setIsRushOrder(true)}
              className={`rounded-xl border p-3 font-mono text-xs transition-all flex items-center justify-center gap-1.5 ${
                isRushOrder
                  ? "border-[#024d37] bg-muted text-foreground font-bold shadow-sm shadow-[#024d37]/15"
                  : "border-border bg-background text-muted-foreground hover:border-[#024d37]/40"
              }`}
            >
              <Sparkles className="h-3 w-3 text-[#024d37]" /> Express Fast-Track
            </button>
          </div>
        </div>
      </div>

      {/* Live Estimate Output Box */}
      <div className="lg:col-span-5 rounded-2xl border border-border bg-muted/60 p-6 flex flex-col justify-between space-y-6">
        <div>
          <div className="border-b border-border pb-4">
            <span className="font-mono text-[11px] text-[#024d37] uppercase block">
              // INSTANT BUDGET BREAKDOWN
            </span>
            <div className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground mt-2 font-mono">
              {formatPrice(totalPKR)}
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              Estimated Delivery: <strong className="text-[#024d37] font-mono">{estimatedDays} Business Days</strong>
            </p>
          </div>

          <div className="mt-4 space-y-2 font-mono text-xs text-muted-foreground">
            <div className="flex justify-between">
              <span>Selected Scope:</span>
              <span className="text-foreground truncate max-w-[180px]">{platform.name}</span>
            </div>
            <div className="flex justify-between">
              <span>Add-ons Included:</span>
              <span className="text-foreground">{selectedAddons.length} Components</span>
            </div>
            <div className="flex justify-between">
              <span>Warranty:</span>
              <span className="text-foreground">30-Day Tech Warranty</span>
            </div>
            {isRushOrder && (
              <div className="flex justify-between text-[#024d37]">
                <span>Speed Acceleration:</span>
                <span>+25% Express SLA</span>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-3 pt-4 border-t border-border font-mono text-xs">
          <div className="flex items-center gap-2 text-muted-foreground text-[11px]">
            <ShieldCheck className="h-4 w-4 text-[#024d37]" />
            <span>Guaranteed sprint milestone deliverables</span>
          </div>

          <ShinyButton
            href={`/contact?service=${encodeURIComponent(platform.name)}&budget=PKR+${totalPKR.toLocaleString()}`}
            className="w-full justify-center"
            showArrow
          >
            Lock-In Quote & Scope
          </ShinyButton>
        </div>
      </div>
    </div>
  );
}
