"use client";

import React, { useState } from "react";
import { X, Play, Monitor, Server, Terminal, ShieldCheck } from "lucide-react";
import { SaaSProduct } from "@/types";

interface DemoModalProps {
  product: SaaSProduct | null;
  isOpen: boolean;
  onClose: () => void;
}

export function DemoModal({ product, isOpen, onClose }: DemoModalProps) {
  const [activeTab, setActiveTab] = useState<"pos" | "inventory" | "desktop">("pos");
  const [cartItems, setCartItems] = useState([
    { id: 1, name: "Panadol Extra 500mg (Pack of 200)", qty: 2, price: 680, batch: "BAT-9941", exp: "12/2027" },
    { id: 2, name: "Augmentin 625mg Tablets", qty: 1, price: 420, batch: "BAT-7812", exp: "08/2026" },
  ]);
  const [fbrSubmitted, setFbrSubmitted] = useState(false);

  if (!isOpen || !product) return null;

  const total = cartItems.reduce((acc, item) => acc + item.qty * item.price, 0);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 md:p-10">
      <div className="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={onClose} />

      <div className="relative z-10 w-full max-w-5xl overflow-hidden rounded-2xl border border-border bg-card text-foreground shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border px-6 py-4">
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-lg font-semibold text-foreground">{product.name} Interactive Simulator</h3>
              <span className="rounded-full border border-border bg-muted px-2 py-0.5 font-mono text-[10px] text-foreground">
                v{product.version}
              </span>
              {product.desktop_supported && (
                <span className="rounded-full border border-border bg-muted px-2 py-0.5 font-mono text-[10px] text-foreground">
                  Electron Desktop
                </span>
              )}
            </div>
            <p className="text-xs text-muted-foreground">{product.tagline}</p>
          </div>

          <button
            onClick={onClose}
            className="rounded-full p-2 text-muted-foreground hover:text-foreground"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Tab Navigation */}
        <div className="flex border-b border-border bg-muted px-6 font-mono text-xs">
          <button
            onClick={() => setActiveTab("pos")}
            className={`border-b-2 py-3 px-4 transition-colors ${
              activeTab === "pos"
                ? "border-foreground text-foreground font-bold"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            [01] POS TERMINAL
          </button>
          <button
            onClick={() => setActiveTab("inventory")}
            className={`border-b-2 py-3 px-4 transition-colors ${
              activeTab === "inventory"
                ? "border-foreground text-foreground font-bold"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            [02] SUPABASE & RLS
          </button>
          <button
            onClick={() => setActiveTab("desktop")}
            className={`border-b-2 py-3 px-4 transition-colors ${
              activeTab === "desktop"
                ? "border-foreground text-foreground font-bold"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            [03] DESKTOP ELECTRON
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-6">
          {activeTab === "pos" && (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 font-mono text-xs">
              <div className="lg:col-span-2 space-y-4">
                <div className="flex items-center justify-between rounded-xl border border-border bg-muted p-3">
                  <span className="text-muted-foreground">TERMINAL: #POS-STATION-01</span>
                  <span className="text-[#024d37] font-bold">● FBR FISCAL: ONLINE</span>
                </div>

                {/* Simulated POS Table */}
                <div className="overflow-hidden rounded-xl border border-border bg-background">
                  <table className="w-full text-left text-xs">
                    <thead className="border-b border-border bg-muted text-[10px] text-muted-foreground uppercase">
                      <tr>
                        <th className="p-3 font-sans">Item / Description</th>
                        <th className="p-3">Batch</th>
                        <th className="p-3">Qty</th>
                        <th className="p-3 text-right">Price</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {cartItems.map((item) => (
                        <tr key={item.id} className="hover:bg-muted/40">
                          <td className="p-3 font-sans font-medium text-foreground">{item.name}</td>
                          <td className="p-3 text-muted-foreground">{item.batch}</td>
                          <td className="p-3 text-foreground">{item.qty}</td>
                          <td className="p-3 text-right font-bold text-foreground">PKR {(item.price * item.qty).toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                <div className="flex gap-2 font-sans">
                  <button
                    onClick={() =>
                      setCartItems([
                        ...cartItems,
                        {
                          id: Date.now(),
                          name: "Brufen 400mg Suspension",
                          qty: 1,
                          price: 180,
                          batch: "BAT-1044",
                          exp: "05/2027",
                        },
                      ])
                    }
                    className="rounded-lg border border-border bg-muted px-3 py-1.5 text-xs text-foreground hover:bg-border"
                  >
                    + Scan Barcode (Mock Item)
                  </button>
                  <button
                    onClick={() => setCartItems([])}
                    className="rounded-lg border border-border px-3 py-1.5 text-xs text-muted-foreground hover:text-destructive"
                  >
                    Clear Bill
                  </button>
                </div>
              </div>

              {/* Checkout Summary */}
              <div className="rounded-xl border border-border bg-muted/60 p-5 flex flex-col justify-between">
                <div>
                  <h4 className="font-sans font-semibold text-foreground mb-4">Transaction Summary</h4>
                  <div className="space-y-2 text-xs">
                    <div className="flex justify-between text-muted-foreground">
                      <span>Subtotal</span>
                      <span>PKR {total.toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between text-muted-foreground">
                      <span>FBR POS Tax (0%)</span>
                      <span>PKR 0</span>
                    </div>
                    <div className="border-t border-border pt-2 flex justify-between text-sm font-bold text-foreground">
                      <span>Total Due</span>
                      <span>PKR {total.toLocaleString()}</span>
                    </div>
                  </div>

                  {fbrSubmitted && (
                    <div className="mt-4 rounded-lg border border-[#024d37]/30 bg-[#024d37]/10 p-3 text-xs text-[#024d37]">
                      <div className="font-semibold">FBR Invoice Generated</div>
                      <div className="text-[10px] mt-0.5">FBR-INV: 99402847291-KHI</div>
                    </div>
                  )}
                </div>

                <div className="mt-6 space-y-2">
                  <button
                    onClick={() => setFbrSubmitted(true)}
                    className="w-full rounded-full bg-foreground py-2.5 font-mono text-xs font-semibold uppercase tracking-[0.12em] text-background hover:opacity-90 transition-opacity"
                  >
                    Generate Bill & QR
                  </button>
                </div>
              </div>
            </div>
          )}

          {activeTab === "inventory" && (
            <div className="space-y-4 text-xs font-mono">
              <div className="rounded-xl border border-border bg-background p-5 space-y-2">
                <span className="text-foreground font-semibold">// SUPABASE POSTGRESQL MULTI-TENANT ARCHITECTURE</span>
                <p className="text-muted-foreground font-sans leading-relaxed">
                  {product.name} operates on an isolated PostgreSQL schema hosted on Supabase, guarded by strict Row Level Security (RLS) policies preventing cross-tenant leakage.
                </p>
                <div className="mt-3 rounded-lg bg-muted p-3 border border-border">
                  <pre className="overflow-x-auto text-foreground text-[11px]">
{`CREATE POLICY "Tenant branch isolation" ON public.inventory
  FOR ALL
  USING (tenant_id = auth.jwt() ->> 'tenant_id');`}
                  </pre>
                </div>
              </div>
            </div>
          )}

          {activeTab === "desktop" && (
            <div className="space-y-4 text-xs font-mono">
              <div className="rounded-xl border border-border bg-background p-5 space-y-2">
                <span className="text-foreground font-semibold">// NATIVE ELECTRON DESKTOP PACKAGING</span>
                <p className="text-muted-foreground font-sans leading-relaxed">
                  Runs as a native desktop binary via Electron. Keeps a local SQLite database that seamlessly syncs with Supabase once online.
                </p>
                <div className="grid grid-cols-2 gap-3 pt-2">
                  <div className="rounded border border-border bg-muted p-3">
                    <span className="font-bold text-foreground">Hardware Drivers:</span>
                    <ul className="mt-1 space-y-1 text-muted-foreground text-[11px]">
                      <li>• ESC/POS 80mm/58mm Printers</li>
                      <li>• Cash Drawer Solenoids</li>
                      <li>• USB Barcode Scanners</li>
                    </ul>
                  </div>
                  <div className="rounded border border-border bg-muted p-3">
                    <span className="font-bold text-foreground">Offline Engine:</span>
                    <ul className="mt-1 space-y-1 text-muted-foreground text-[11px]">
                      <li>• 100% Offline SQLite Cache</li>
                      <li>• Auto Cloud Re-sync</li>
                      <li>• Auto-update distribution</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between border-t border-border bg-muted px-6 py-4 font-mono text-xs">
          <span className="text-muted-foreground">Target: {product.target_audience}</span>
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="rounded-full border border-border px-4 py-1.5 text-muted-foreground hover:text-foreground"
            >
              Close
            </button>
            <a
              href="/contact"
              className="rounded-full bg-foreground px-4 py-1.5 text-background font-semibold uppercase tracking-[0.12em]"
            >
              Request Deployment
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}
