'use client';

import React, { useState } from 'react';
import { DemoStoreItem } from '@/lib/saas-admin/demoData';

interface StoreDetailsModalProps {
  store: DemoStoreItem | null;
  onClose: () => void;
  onPlanChangeRequest: (store: DemoStoreItem) => void;
}

export default function StoreDetailsModal({
  store,
  onClose,
  onPlanChangeRequest,
}: StoreDetailsModalProps) {
  const [activeTab, setActiveTab] = useState<'overview' | 'billing' | 'usage' | 'activity'>('overview');

  if (!store) return null;

  const planBadgeColor = (plan: string) => {
    switch (plan.toLowerCase()) {
      case 'accelerate':
        return 'bg-purple-50 text-purple-700 border-purple-200';
      case 'growth':
        return 'bg-blue-50 text-blue-700 border-blue-200';
      case 'basic':
      case 'free':
        return 'bg-emerald-50 text-emerald-700 border-emerald-200';
      default:
        return 'bg-slate-100 text-slate-700 border-slate-200';
    }
  };

  const statusBadge = (status: string) => {
    if (status === 'installed') {
      return (
        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
          <span>Installed</span>
        </span>
      );
    }
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-600 border border-slate-200">
        <span className="w-1.5 h-1.5 rounded-full bg-slate-400" />
        <span className="capitalize">{status}</span>
      </span>
    );
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6 animate-in fade-in">
      <div className="bg-white rounded-3xl border border-slate-200 shadow-2xl w-full max-w-4xl overflow-hidden flex flex-col max-h-[92vh] animate-in zoom-in-95">
        {/* Header Banner */}
        <div className="p-6 border-b border-slate-200/80 bg-slate-50/60 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-start sm:items-center gap-4">
            <div className="w-12 h-12 rounded-2xl bg-slate-900 text-white font-black text-xl flex items-center justify-center shadow-sm shrink-0">
              <i className="fa-brands fa-shopify text-2xl" />
            </div>
            <div>
              <div className="flex flex-wrap items-center gap-2">
                <h2 className="text-xl font-extrabold text-slate-900 tracking-tight">
                  {store.shop_name}
                </h2>
                {statusBadge(store.status)}
                {store.is_demo ? (
                  <span className="px-2 py-0.5 rounded-full text-[10px] font-black uppercase tracking-wider bg-blue-50 text-blue-700 border border-blue-200">
                    Demo Store
                  </span>
                ) : (
                  <span className="px-2 py-0.5 rounded-full text-[10px] font-black uppercase tracking-wider bg-emerald-50 text-emerald-800 border border-emerald-200">
                    Live Shopify Shop
                  </span>
                )}
              </div>
              <div className="flex flex-wrap items-center gap-2 sm:gap-4 text-xs text-slate-500 mt-1">
                <span className="font-mono text-slate-700 font-bold">{store.shopify_domain}</span>
                <span>&bull;</span>
                <span className="text-slate-400 font-mono text-[11px]">{store.shopify_shop_id}</span>
                <span>&bull;</span>
                <span>{store.country}</span>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2 self-end sm:self-center">
            <button
              onClick={() => onPlanChangeRequest(store)}
              className="px-3.5 py-2 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-2xs flex items-center gap-1.5 transition-colors cursor-pointer"
            >
              <i className="fa-solid fa-arrows-rotate text-xs" />
              <span>Change Plan</span>
            </button>
            <button
              onClick={onClose}
              className="w-9 h-9 rounded-xl border border-slate-200 text-slate-400 hover:text-slate-600 hover:bg-slate-100 flex items-center justify-center cursor-pointer"
            >
              <i className="fa-solid fa-xmark text-sm" />
            </button>
          </div>
        </div>

        {/* Tab Navigation */}
        <div className="px-6 border-b border-slate-200/80 bg-white flex items-center gap-6 text-xs font-bold text-slate-500 overflow-x-auto">
          {[
            { id: 'overview', label: 'Store Overview', icon: 'fa-solid fa-circle-info' },
            { id: 'billing', label: 'Subscription & Billing History', icon: 'fa-regular fa-credit-card' },
            { id: 'usage', label: 'App Usage & Feeds', icon: 'fa-solid fa-layer-group' },
            { id: 'activity', label: 'Store Activity Logs', icon: 'fa-solid fa-clock-rotate-left' },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`py-3.5 flex items-center gap-2 border-b-2 transition-all cursor-pointer whitespace-nowrap ${
                activeTab === tab.id
                  ? 'border-theme text-theme'
                  : 'border-transparent hover:text-slate-900'
              }`}
            >
              <i className={tab.icon} />
              <span>{tab.label}</span>
            </button>
          ))}
        </div>

        {/* Modal Body / Tab Contents */}
        <div className="p-6 overflow-y-auto flex-1 space-y-6">
          {/* TAB 1: OVERVIEW */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              {/* 4 Identity Mini Cards */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200/70 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Store Owner
                  </span>
                  <div className="text-xs font-black text-slate-900 truncate">{store.owner_name}</div>
                  <div className="text-[11px] text-blue-600 truncate">{store.owner_email}</div>
                </div>

                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200/70 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Active Plan Tier
                  </span>
                  <div className="flex items-center gap-1.5">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-bold border ${planBadgeColor(store.plan)}`}>
                      {store.plan_name}
                    </span>
                  </div>
                  <div className="text-[11px] text-slate-500 font-medium">
                    ${store.plan_price} / {store.billing_cycle}
                  </div>
                </div>

                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200/70 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Installation Date
                  </span>
                  <div className="text-xs font-black text-slate-900">
                    {new Date(store.installed_at).toLocaleDateString()}
                  </div>
                  <div className="text-[11px] text-slate-400">
                    {new Date(store.installed_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                  </div>
                </div>

                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200/70 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Last Activity
                  </span>
                  <div className="text-xs font-black text-emerald-700 flex items-center gap-1.5">
                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                    <span>Active recently</span>
                  </div>
                  <div className="text-[11px] text-slate-400">
                    {new Date(store.last_active_at).toLocaleDateString()}
                  </div>
                </div>
              </div>

              {/* Meta Commerce Connection Status */}
              <div className="p-5 rounded-2xl border border-slate-200 bg-white space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <i className="fa-brands fa-meta text-blue-600 text-lg" />
                    <h4 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                      Meta Assets &amp; Advantage+ Sync
                    </h4>
                  </div>
                  {store.meta.connected ? (
                    <span className="px-2.5 py-0.5 rounded-full text-[10px] font-extrabold bg-emerald-50 text-emerald-800 border border-emerald-200 flex items-center gap-1">
                      <i className="fa-solid fa-check text-[10px]" />
                      <span>Connected &bull; Active</span>
                    </span>
                  ) : (
                    <span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-slate-100 text-slate-600 border border-slate-200">
                      Not Connected
                    </span>
                  )}
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
                  <div className="p-3 rounded-xl bg-slate-50 border border-slate-100">
                    <span className="text-[10px] text-slate-400 uppercase font-semibold">Business Manager</span>
                    <div className="font-bold text-slate-900 truncate mt-0.5">
                      {store.meta.business_name || 'N/A'}
                    </div>
                  </div>
                  <div className="p-3 rounded-xl bg-slate-50 border border-slate-100">
                    <span className="text-[10px] text-slate-400 uppercase font-semibold">Pixel Master ID</span>
                    <div className="font-mono text-slate-900 truncate mt-0.5">
                      {store.meta.pixel_id || 'N/A'}
                    </div>
                  </div>
                  <div className="p-3 rounded-xl bg-slate-50 border border-slate-100">
                    <span className="text-[10px] text-slate-400 uppercase font-semibold">Feed / Catalog</span>
                    <div className="font-bold text-slate-900 truncate mt-0.5">
                      {store.meta.catalog_name || 'N/A'}
                    </div>
                  </div>
                </div>
              </div>

              {/* App Permissions Scopes */}
              <div className="p-5 rounded-2xl border border-slate-200 bg-white space-y-3">
                <h4 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                  Granted Shopify OAuth Permissions
                </h4>
                <div className="flex flex-wrap gap-2">
                  {store.permissions.map((perm) => (
                    <span
                      key={perm}
                      className="px-2.5 py-1 rounded-lg text-xs font-mono font-medium bg-slate-100 text-slate-700 border border-slate-200/80"
                    >
                      {perm}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: BILLING & PAYMENT HISTORY */}
          {activeTab === 'billing' && (
            <div className="space-y-6">
              <div className="p-5 rounded-2xl bg-gradient-to-r from-slate-900 to-slate-800 text-white space-y-4">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div>
                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                      Current Subscription Status
                    </span>
                    <div className="text-xl font-black capitalize mt-0.5 flex items-center gap-2">
                      <span>{store.subscription_status} Subscription</span>
                      <span className="text-xs font-bold px-2.5 py-0.5 rounded-full bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
                        ${store.monthly_revenue}/mo
                      </span>
                    </div>
                  </div>
                  <div className="text-right">
                    <span className="text-[10px] text-slate-400 uppercase font-semibold">Billing Interval</span>
                    <div className="text-xs font-bold capitalize text-slate-200">{store.billing_cycle} Recurring</div>
                  </div>
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="text-xs font-bold text-slate-900 uppercase tracking-wider flex items-center justify-between">
                  <span>Verified Shopify Billing Transactions</span>
                  <span className="text-[11px] text-slate-400 font-normal">
                    {store.billingHistory.length} Receipts Found
                  </span>
                </h4>

                {store.billingHistory.length === 0 ? (
                  <div className="p-8 text-center text-xs text-slate-400 bg-slate-50 rounded-2xl border border-slate-200">
                    No verified paid charges recorded. Free plan store.
                  </div>
                ) : (
                  <div className="border border-slate-200 rounded-2xl overflow-hidden">
                    <table className="w-full text-left text-xs text-slate-600">
                      <thead className="bg-slate-50 text-slate-400 uppercase text-[10px] font-bold border-b border-slate-200">
                        <tr>
                          <th className="py-3 px-4">Date</th>
                          <th className="py-3 px-4">Plan</th>
                          <th className="py-3 px-4">Charge ID</th>
                          <th className="py-3 px-4">Amount</th>
                          <th className="py-3 px-4 text-right">Verification Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {store.billingHistory.map((b) => (
                          <tr key={b.id} className="hover:bg-slate-50">
                            <td className="py-3 px-4 font-medium text-slate-800">
                              {new Date(b.date).toLocaleDateString()}
                            </td>
                            <td className="py-3 px-4 font-bold text-slate-900">{b.plan}</td>
                            <td className="py-3 px-4 font-mono text-[11px] text-slate-400">{b.chargeId}</td>
                            <td className="py-3 px-4 font-black text-slate-900">${b.amount} {b.currency}</td>
                            <td className="py-3 px-4 text-right">
                              <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
                                Verified
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* TAB 3: APP USAGE & FEEDS */}
          {activeTab === 'usage' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="p-5 rounded-2xl bg-white border border-slate-200 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Synced Catalog Products
                  </span>
                  <div className="text-2xl font-black text-purple-600">
                    {store.stats.productsCount.toLocaleString()}
                  </div>
                  <div className="text-[11px] text-slate-500 font-medium">SKU feeds active at Meta</div>
                </div>

                <div className="p-5 rounded-2xl bg-white border border-slate-200 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Meta Pixels Connected
                  </span>
                  <div className="text-2xl font-black text-blue-600">
                    {store.stats.pixelsCount}
                  </div>
                  <div className="text-[11px] text-slate-500 font-medium">Master &amp; Collection Pixels</div>
                </div>

                <div className="p-5 rounded-2xl bg-white border border-slate-200 space-y-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Dispatched CAPI Events
                  </span>
                  <div className="text-2xl font-black text-cyan-600">
                    {store.stats.eventsCount.toLocaleString()}
                  </div>
                  <div className="text-[11px] text-slate-500 font-medium">Server-side conversions sent</div>
                </div>
              </div>

              <div className="p-5 rounded-2xl border border-slate-200 bg-slate-50 space-y-2">
                <span className="text-xs font-bold text-slate-900 uppercase tracking-wider flex items-center gap-2">
                  <i className="fa-solid fa-gauge-high text-emerald-600" />
                  <span>Meta Event Match Quality (EMQ)</span>
                </span>
                <p className="text-xs text-slate-600">
                  Store events sent with SHA-256 normalized customer hashing (email, phone, client IP, user agent) achieving a <strong>9.2/10 Excellent Rating</strong> on Meta Ads Manager.
                </p>
              </div>
            </div>
          )}

          {/* TAB 4: STORE ACTIVITY LOGS */}
          {activeTab === 'activity' && (
            <div className="space-y-4">
              <h4 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                Chronological Store Lifecycle &amp; Webhook Events
              </h4>

              <div className="relative pl-6 space-y-6 before:absolute before:left-2 before:top-2 before:bottom-2 before:w-0.5 before:bg-slate-200">
                {store.activityHistory.map((act) => (
                  <div key={act.id} className="relative">
                    <span className="absolute -left-6 top-1 w-3 h-3 rounded-full bg-theme border-2 border-white" />
                    <div className="text-xs font-bold text-slate-900">{act.description}</div>
                    <div className="flex items-center gap-2 text-[10px] text-slate-400 mt-0.5">
                      <span>{new Date(act.date).toLocaleString()}</span>
                      <span>&bull;</span>
                      <span className="font-semibold text-slate-500 uppercase">{act.actor}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Modal Footer Actions */}
        <div className="p-4 sm:px-6 border-t border-slate-200 bg-slate-50 flex items-center justify-between">
          <div className="text-xs text-slate-500">
            Store ID: <span className="font-mono text-slate-700 font-bold">{store.id}</span>
          </div>
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-xl text-xs font-bold bg-white border border-slate-200 hover:bg-slate-100 text-slate-700 cursor-pointer"
          >
            Close Profile
          </button>
        </div>
      </div>
    </div>
  );
}
