'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { appRoute } from '@/lib/utils/asset';

interface DashboardMetrics {
  products: {
    total: number;
    synced: number;
    excluded: number;
    outOfStock: number;
    warning: number;
    error: number;
    inventory: number;
    catalogValue: number;
  };
  meta: {
    connected: boolean;
    businessName: string | null;
    businessId: string | null;
    pageName: string | null;
    pageId: string | null;
    instagramName: string | null;
    instagramId: string | null;
    adAccountName: string | null;
    adAccountId: string | null;
    catalogName: string | null;
    catalogId: string | null;
    pixelName: string | null;
    pixelId: string | null;
    onboardingCompleted: boolean;
    activePixelsCount: number;
    activeCatalogsCount: number;
    status: string;
    hasToken: boolean;
  };
  syncHistory: Array<{
    id: string;
    sync_type: string;
    status: string;
    total_products: number;
    processed_products: number;
    failed_products: number;
    started_at: string;
    completed_at?: string | null;
    error_message?: string | null;
  }>;
  recentProducts: Array<{
    id: string;
    title: string;
    variant_title?: string | null;
    sku?: string | null;
    price: number;
    currency: string;
    availability: string;
    inventory_quantity: number;
    image_url: string;
    is_excluded?: boolean;
    status: string;
  }>;
}

export default function DashboardPage() {
  const searchParams = useSearchParams();
  const shopParam = searchParams.get('shop') || '';

  const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
  const [storeInfo, setStoreInfo] = useState<{ domain: string; timezone: string; currency: string } | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSyncingProducts, setIsSyncingProducts] = useState(false);
  const [syncFeedback, setSyncFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null);

  const getHref = (path: string) => {
    return appRoute(path, searchParams);
  };

  const fetchDashboardData = async () => {
    try {
      setIsLoading(true);
      const url = shopParam ? `/api/shops?shop=${encodeURIComponent(shopParam)}` : '/api/shops';
      const res = await fetch(url);
      const data = await res.json();
      if (data.success) {
        if (data.store) {
          setStoreInfo({
            domain: data.store.domain || '',
            timezone: data.store.timezone || 'UTC',
            currency: data.store.currency || 'USD',
          });
        }
        if (data.metrics) {
          setMetrics(data.metrics);
        }
      }
    } catch (err) {
      console.error('Failed to load dashboard:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchDashboardData();
  }, [shopParam]);

  const handleSyncShopifyProducts = async () => {
    try {
      setIsSyncingProducts(true);
      setSyncFeedback(null);
      const url = shopParam ? `/api/shopify/products/sync?shop=${encodeURIComponent(shopParam)}` : '/api/shopify/products/sync';
      const res = await fetch(url, { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        setSyncFeedback({
          type: 'success',
          message: data.message || `Successfully synced ${data.totalProducts} products from Shopify.`,
        });
        await fetchDashboardData();
      } else {
        setSyncFeedback({
          type: 'error',
          message: data.error || 'Failed to sync Shopify products',
        });
      }
    } catch (err: any) {
      setSyncFeedback({
        type: 'error',
        message: err.message || 'Network error syncing products',
      });
    } finally {
      setIsSyncingProducts(false);
    }
  };

  if (isLoading) {
    return (
      <AppLayout currentRoute="/dashboard">
        <div className="flex items-center justify-center py-20">
          <div className="flex flex-col items-center gap-3">
            <div className="w-8 h-8 border-3 border-blue-600 border-t-transparent rounded-full animate-spin" />
            <p className="text-xs font-semibold text-slate-500">Loading Dashboard Metrics...</p>
          </div>
        </div>
      </AppLayout>
    );
  }

  const metaConn = metrics?.meta;
  const prodStats = metrics?.products;
  const syncHistory = metrics?.syncHistory || [];
  const recentProducts = metrics?.recentProducts || [];

  return (
    <AppLayout currentRoute="/dashboard">
      <div className="space-y-6">
        {/* Top Header Row */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl sm:text-2xl font-black text-slate-900 tracking-tight">
              Store Dashboard
            </h1>
            <p className="text-xs text-slate-500 font-medium mt-0.5">
              Live status for <span className="font-bold text-slate-700">{storeInfo?.domain || 'Shopify Store'}</span>
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              type="button"
              onClick={handleSyncShopifyProducts}
              disabled={isSyncingProducts}
              className="px-4 py-2 rounded-xl text-xs font-bold bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 shadow-2xs transition-colors flex items-center gap-2 disabled:opacity-50 cursor-pointer"
            >
              <i className={`fa-solid fa-arrows-rotate text-xs text-blue-600 ${isSyncingProducts ? 'animate-spin' : ''}`} />
              <span>{isSyncingProducts ? 'Syncing...' : 'Sync Products from Shopify'}</span>
            </button>

            <Link
              href={getHref('/catalog/create')}
              className="px-4 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white shadow-sm transition-colors flex items-center gap-1.5"
            >
              <i className="fa-solid fa-plus text-xs" />
              <span>Create Catalog</span>
            </Link>
          </div>
        </div>

        {/* Sync Feedback Message */}
        {syncFeedback && (
          <div
            className={`p-3.5 rounded-2xl border text-xs flex items-center justify-between gap-2 animate-in fade-in duration-200 ${
              syncFeedback.type === 'success'
                ? 'bg-emerald-50 border-emerald-200 text-emerald-800'
                : 'bg-red-50 border-red-200 text-red-800'
            }`}
          >
            <div className="flex items-center gap-2">
              <i className={`fa-solid ${syncFeedback.type === 'success' ? 'fa-circle-check text-emerald-600' : 'fa-circle-exclamation text-red-600'}`} />
              <span>{syncFeedback.message}</span>
            </div>
            <button
              type="button"
              onClick={() => setSyncFeedback(null)}
              className="text-slate-400 hover:text-slate-600"
            >
              <i className="fa-solid fa-xmark" />
            </button>
          </div>
        )}

        {/* ---------------------------------------------------- */}
        {/* SECTION 1: CONNECTION STATUS OVERVIEW               */}
        {/* ---------------------------------------------------- */}
        <div>
          <h2 className="text-xs font-extrabold uppercase tracking-wider text-slate-400 mb-3 flex items-center gap-1.5">
            <i className="fa-solid fa-link text-[10px] text-blue-500" />
            <span>Connection Status</span>
          </h2>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* 1. Meta Business Account */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs space-y-2">
              <div className="flex items-center justify-between">
                <div className="w-8 h-8 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center">
                  <i className="fa-brands fa-meta text-sm" />
                </div>
                <span
                  className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider ${
                    metaConn?.connected
                      ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                      : 'bg-amber-50 text-amber-700 border border-amber-200'
                  }`}
                >
                  {metaConn?.connected ? 'Connected' : 'Disconnected'}
                </span>
              </div>
              <div>
                <p className="text-[11px] text-slate-400 font-medium">Meta Business Portfolio</p>
                <h3 className="text-sm font-bold text-slate-900 truncate">
                  {metaConn?.businessName || (metaConn?.connected ? 'Active Portfolio' : 'Not Connected')}
                </h3>
                <p className="text-[10px] font-mono text-slate-400 truncate mt-0.5">
                  ID: {metaConn?.businessId || '—'}
                </p>
              </div>
              <div className="pt-1">
                <Link
                  href={getHref('/integration')}
                  className="text-[11px] font-bold text-blue-600 hover:underline flex items-center gap-1"
                >
                  <span>{metaConn?.connected ? 'Manage Assets' : 'Connect Account'}</span>
                  <i className="fa-solid fa-chevron-right text-[9px]" />
                </Link>
              </div>
            </div>

            {/* 2. Facebook & Instagram Assets */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs space-y-2">
              <div className="flex items-center justify-between">
                <div className="w-8 h-8 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center">
                  <i className="fa-brands fa-instagram text-sm" />
                </div>
                <span
                  className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider ${
                    metaConn?.pageName || metaConn?.instagramName
                      ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                      : 'bg-slate-100 text-slate-600'
                  }`}
                >
                  {metaConn?.pageName || metaConn?.instagramName ? 'Configured' : 'Optional'}
                </span>
              </div>
              <div>
                <p className="text-[11px] text-slate-400 font-medium">FB Page &amp; Instagram</p>
                <h3 className="text-sm font-bold text-slate-900 truncate">
                  {metaConn?.pageName || metaConn?.instagramName || 'No Assets Linked'}
                </h3>
                <p className="text-[10px] text-slate-400 truncate mt-0.5">
                  IG: {metaConn?.instagramName || 'None'} &bull; Page: {metaConn?.pageName || 'None'}
                </p>
              </div>
              <div className="pt-1">
                <Link
                  href={getHref('/integration')}
                  className="text-[11px] font-bold text-blue-600 hover:underline flex items-center gap-1"
                >
                  <span>Select Assets</span>
                  <i className="fa-solid fa-chevron-right text-[9px]" />
                </Link>
              </div>
            </div>

            {/* 3. Pixel Management */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs space-y-2">
              <div className="flex items-center justify-between">
                <div className="w-8 h-8 rounded-xl bg-sky-50 text-sky-600 flex items-center justify-center">
                  <i className="fa-brands fa-facebook text-sm" />
                </div>
                <span
                  className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider ${
                    (metaConn?.activePixelsCount || 0) > 0
                      ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                      : 'bg-slate-100 text-slate-600'
                  }`}
                >
                  {metaConn?.activePixelsCount || 0} Active
                </span>
              </div>
              <div>
                <p className="text-[11px] text-slate-400 font-medium">Tracking Pixels</p>
                <h3 className="text-sm font-bold text-slate-900 truncate">
                  {metaConn?.pixelName || ((metaConn?.activePixelsCount || 0) > 0 ? `${metaConn?.activePixelsCount} Pixels Active` : 'No Pixels')}
                </h3>
                <p className="text-[10px] font-mono text-slate-400 truncate mt-0.5">
                  Pixel ID: {metaConn?.pixelId || '—'}
                </p>
              </div>
              <div className="pt-1">
                <Link
                  href={getHref('/pixel')}
                  className="text-[11px] font-bold text-blue-600 hover:underline flex items-center gap-1"
                >
                  <span>Manage Pixels</span>
                  <i className="fa-solid fa-chevron-right text-[9px]" />
                </Link>
              </div>
            </div>

            {/* 4. Shopify Store */}
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs space-y-2">
              <div className="flex items-center justify-between">
                <div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
                  <i className="fa-brands fa-shopify text-sm" />
                </div>
                <span className="text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider bg-emerald-50 text-emerald-700 border border-emerald-200">
                  Installed
                </span>
              </div>
              <div>
                <p className="text-[11px] text-slate-400 font-medium">Shopify Connection</p>
                <h3 className="text-sm font-bold text-slate-900 truncate">
                  {storeInfo?.domain || 'Connected Store'}
                </h3>
                <p className="text-[10px] text-slate-400 truncate mt-0.5">
                  Currency: {storeInfo?.currency || 'USD'} &bull; TZ: {storeInfo?.timezone || 'UTC'}
                </p>
              </div>
              <div className="pt-1">
                <Link
                  href={getHref('/settings')}
                  className="text-[11px] font-bold text-blue-600 hover:underline flex items-center gap-1"
                >
                  <span>App Settings</span>
                  <i className="fa-solid fa-chevron-right text-[9px]" />
                </Link>
              </div>
            </div>
          </div>
        </div>

        {/* ---------------------------------------------------- */}
        {/* SECTION 2: PRODUCTS OVERVIEW METRICS                */}
        {/* ---------------------------------------------------- */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-xs font-extrabold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
              <i className="fa-solid fa-boxes-stacked text-[10px] text-blue-500" />
              <span>Products Overview</span>
            </h2>
            <Link
              href={getHref('/products')}
              className="text-xs font-bold text-blue-600 hover:underline flex items-center gap-1"
            >
              <span>View Product Management</span>
              <i className="fa-solid fa-arrow-right text-[10px]" />
            </Link>
          </div>

          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs">
              <p className="text-xs text-slate-500 font-medium">Total Products</p>
              <h3 className="text-2xl font-black text-slate-900 mt-1">
                {prodStats?.total ?? 0}
              </h3>
              <p className="text-[11px] text-slate-400 mt-0.5">
                Variants in store catalog
              </p>
            </div>

            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs">
              <p className="text-xs text-emerald-700 font-medium">Included for Meta Sync</p>
              <h3 className="text-2xl font-black text-emerald-600 mt-1">
                {prodStats?.synced ?? 0}
              </h3>
              <p className="text-[11px] text-slate-400 mt-0.5">
                Active &amp; published to feeds
              </p>
            </div>

            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs">
              <p className="text-xs text-slate-500 font-medium">Excluded Products</p>
              <h3 className="text-2xl font-black text-slate-600 mt-1">
                {prodStats?.excluded ?? 0}
              </h3>
              <p className="text-[11px] text-slate-400 mt-0.5">
                Filtered out by tags/rules
              </p>
            </div>

            <div className="bg-white rounded-2xl border border-slate-200/90 p-4.5 shadow-2xs">
              <p className="text-xs text-amber-600 font-medium">Out of Stock</p>
              <h3 className="text-2xl font-black text-amber-600 mt-1">
                {prodStats?.outOfStock ?? 0}
              </h3>
              <p className="text-[11px] text-slate-400 mt-0.5">
                Zero inventory variants
              </p>
            </div>
          </div>
        </div>

        {/* ---------------------------------------------------- */}
        {/* SECTION 3: RECENT SYNC HISTORY (NO STATIC DATA)      */}
        {/* ---------------------------------------------------- */}
        <div className="bg-white rounded-2xl border border-slate-200/90 shadow-2xs overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center">
                <i className="fa-solid fa-clock-rotate-left text-xs" />
              </div>
              <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                Recent Sync History
              </h3>
            </div>
            <Link
              href={getHref('/catalog')}
              className="text-xs font-semibold text-blue-600 hover:underline"
            >
              Manage Catalogs &rarr;
            </Link>
          </div>

          {syncHistory.length === 0 ? (
            /* EMPTY MESSAGE: NO STATIC DATA (Requirement) */
            <div className="p-8 text-center space-y-3">
              <div className="w-12 h-12 rounded-2xl bg-slate-100 text-slate-400 flex items-center justify-center mx-auto">
                <i className="fa-solid fa-arrows-rotate text-lg" />
              </div>
              <div className="space-y-1">
                <h4 className="text-xs font-bold text-slate-800">No Sync History Found</h4>
                <p className="text-[11px] text-slate-400 max-w-sm mx-auto">
                  No catalog synchronizations have run yet. Once a catalog sync is triggered, details and progress logs will be displayed here.
                </p>
              </div>
              <div className="pt-1">
                <Link
                  href={getHref('/catalog')}
                  className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white shadow-2xs"
                >
                  <i className="fa-solid fa-layer-group text-xs" />
                  <span>Go to Catalogs</span>
                </Link>
              </div>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs">
                <thead className="bg-slate-50/80 border-b border-slate-100 text-slate-400 font-bold uppercase text-[10px]">
                  <tr>
                    <th className="py-3 px-5">Sync Type</th>
                    <th className="py-3 px-5">Status</th>
                    <th className="py-3 px-5">Total Items</th>
                    <th className="py-3 px-5">Processed</th>
                    <th className="py-3 px-5">Failed</th>
                    <th className="py-3 px-5">Started At</th>
                    <th className="py-3 px-5 text-right">Details</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {syncHistory.map((s) => (
                    <tr key={s.id} className="hover:bg-slate-50/60 transition-colors">
                      <td className="py-3 px-5 font-semibold text-slate-900 capitalize">
                        {s.sync_type.replace('_', ' ')}
                      </td>
                      <td className="py-3 px-5">
                        <span
                          className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase tracking-wider ${
                            s.status === 'completed'
                              ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                              : s.status === 'failed'
                              ? 'bg-red-50 text-red-700 border border-red-200'
                              : 'bg-blue-50 text-blue-700 border border-blue-200'
                          }`}
                        >
                          {s.status}
                        </span>
                      </td>
                      <td className="py-3 px-5 text-slate-700">{s.total_products}</td>
                      <td className="py-3 px-5 text-emerald-600 font-semibold">{s.processed_products}</td>
                      <td className="py-3 px-5 text-red-600 font-semibold">{s.failed_products}</td>
                      <td className="py-3 px-5 text-slate-500">
                        {s.started_at ? new Date(s.started_at).toLocaleString() : '—'}
                      </td>
                      <td className="py-3 px-5 text-right text-slate-400 font-mono text-[10px]">
                        {s.error_message ? (
                          <span className="text-red-500 font-sans truncate max-w-[150px] inline-block" title={s.error_message}>
                            {s.error_message}
                          </span>
                        ) : (
                          'OK'
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* ---------------------------------------------------- */}
        {/* SECTION 4: RECENT PRODUCTS (NO STATIC DATA)          */}
        {/* ---------------------------------------------------- */}
        <div className="bg-white rounded-2xl border border-slate-200/90 shadow-2xs overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center">
                <i className="fa-solid fa-box text-xs" />
              </div>
              <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider">
                Store Products
              </h3>
            </div>
            <Link
              href={getHref('/products')}
              className="text-xs font-semibold text-blue-600 hover:underline"
            >
              All Products &rarr;
            </Link>
          </div>

          {recentProducts.length === 0 ? (
            /* EMPTY MESSAGE: NO STATIC DATA (Requirement) */
            <div className="p-8 text-center space-y-3">
              <div className="w-12 h-12 rounded-2xl bg-slate-100 text-slate-400 flex items-center justify-center mx-auto">
                <i className="fa-solid fa-boxes-stacked text-lg" />
              </div>
              <div className="space-y-1">
                <h4 className="text-xs font-bold text-slate-800">No Products Synchronized Yet</h4>
                <p className="text-[11px] text-slate-400 max-w-sm mx-auto">
                  Click the button below to import your product catalog directly from your Shopify Admin API.
                </p>
              </div>
              <div className="pt-1">
                <button
                  type="button"
                  onClick={handleSyncShopifyProducts}
                  disabled={isSyncingProducts}
                  className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold bg-blue-600 hover:bg-blue-700 text-white shadow-2xs cursor-pointer disabled:opacity-50"
                >
                  <i className={`fa-solid fa-arrows-rotate text-xs ${isSyncingProducts ? 'animate-spin' : ''}`} />
                  <span>Sync Products from Shopify</span>
                </button>
              </div>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs">
                <thead className="bg-slate-50/80 border-b border-slate-100 text-slate-400 font-bold uppercase text-[10px]">
                  <tr>
                    <th className="py-3 px-5">Product</th>
                    <th className="py-3 px-5">SKU</th>
                    <th className="py-3 px-5">Price</th>
                    <th className="py-3 px-5">Inventory</th>
                    <th className="py-3 px-5">Availability</th>
                    <th className="py-3 px-5 text-right">Meta Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {recentProducts.map((p) => (
                    <tr key={p.id} className="hover:bg-slate-50/60 transition-colors">
                      <td className="py-3 px-5">
                        <div className="flex items-center gap-3">
                          <img
                            src={p.image_url || 'https://via.placeholder.com/40x40?text=No+Img'}
                            alt={p.title}
                            className="w-9 h-9 rounded-lg object-cover border border-slate-200 shrink-0"
                          />
                          <div className="min-w-0">
                            <span className="font-bold text-slate-900 truncate block max-w-xs">{p.title}</span>
                            {p.variant_title && (
                              <span className="text-[10px] text-slate-400 truncate block">{p.variant_title}</span>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-5 font-mono text-slate-600 text-[11px]">{p.sku || '—'}</td>
                      <td className="py-3 px-5 font-semibold text-slate-900">
                        {p.currency} {Number(p.price).toFixed(2)}
                      </td>
                      <td className="py-3 px-5 text-slate-700">{p.inventory_quantity}</td>
                      <td className="py-3 px-5">
                        <span
                          className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase ${
                            p.availability === 'in stock'
                              ? 'bg-emerald-50 text-emerald-700'
                              : 'bg-amber-50 text-amber-700'
                          }`}
                        >
                          {p.availability}
                        </span>
                      </td>
                      <td className="py-3 px-5 text-right">
                        <span
                          className={`text-[10px] px-2 py-0.5 rounded-full font-bold uppercase ${
                            p.is_excluded
                              ? 'bg-slate-100 text-slate-600'
                              : 'bg-emerald-50 text-emerald-700'
                          }`}
                        >
                          {p.is_excluded ? 'Excluded' : 'Included'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </AppLayout>
  );
}
