'use client';

import { useState } from 'react';
import { Search, X, CheckCircle2, Circle, ExternalLink, Zap, ShoppingCart, Truck, Users, CreditCard, MessageSquare, BarChart3, Star, ArrowRight, BookOpen, ChevronDown } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface Integration {
  id: string;
  name: string;
  description: string;
  category: string;
  logo: string;
  logoColor: string;
  connected: boolean;
  popular?: boolean;
  setupSteps: { title: string; description: string }[];
  docsUrl?: string;
}

const integrations: Integration[] = [
  {
    id: 'square',
    name: 'Square POS',
    description: 'Sync orders, menu items, and inventory directly from your Square point-of-sale system.',
    category: 'POS Systems',
    logo: 'SQ',
    logoColor: 'hsl(210, 100%, 40%)',
    connected: false,
    popular: true,
    setupSteps: [
      { title: 'Create a Square Developer Account', description: 'Go to developer.squareup.com and sign in with your Square account. Navigate to the Applications section.' },
      { title: 'Generate API Credentials', description: 'Create a new application and copy your Application ID and Access Token from the Credentials tab.' },
      { title: 'Enter Credentials in RestroAgent', description: 'Paste your Application ID and Access Token in the fields below and click Authorize.' },
      { title: 'Select Location', description: 'Choose which Square location to sync with this RestroAgent branch. Each branch maps to one Square location.' },
      { title: 'Configure Sync Settings', description: 'Choose what data to sync: menu items, inventory levels, orders, and customer data. Enable real-time webhooks for live updates.' },
    ],
  },
  {
    id: 'toast',
    name: 'Toast POS',
    description: 'Connect Toast to automatically import your menu, manage orders, and track sales in real time.',
    category: 'POS Systems',
    logo: 'TO',
    logoColor: 'hsl(22, 89%, 48%)',
    connected: false,
    popular: true,
    setupSteps: [
      { title: 'Access Toast Developer Portal', description: 'Log in to your Toast account and navigate to Settings > Integrations > Developer Portal.' },
      { title: 'Create an API Token', description: 'Under API Access, generate a new token with read/write permissions for Orders, Menu, and Customers.' },
      { title: 'Copy Restaurant GUID', description: 'Find your Restaurant GUID in Toast under Settings > Restaurant Information. You will need this for the connection.' },
      { title: 'Connect in RestroAgent', description: 'Enter your API Token and Restaurant GUID in the connection form and click Connect.' },
      { title: 'Map Menu Categories', description: 'After connecting, map your Toast menu categories to RestroAgent categories for accurate AI responses.' },
    ],
  },
  {
    id: 'stripe',
    name: 'Stripe Payments',
    description: 'Accept online payments, manage subscriptions, and process refunds through Stripe.',
    category: 'Payment Gateways',
    logo: 'ST',
    logoColor: 'hsl(270, 60%, 50%)',
    connected: false,
    setupSteps: [
      { title: 'Log in to Stripe Dashboard', description: 'Go to dashboard.stripe.com and navigate to Developers > API Keys.' },
      { title: 'Copy Publishable & Secret Keys', description: 'Copy both your Publishable Key (pk_live_...) and Secret Key (sk_live_...). Never share your secret key.' },
      { title: 'Add Keys to RestroAgent', description: 'Paste both keys in the Stripe connection form. The publishable key is used for the frontend checkout, the secret key for server-side operations.' },
      { title: 'Configure Webhook Endpoint', description: 'In Stripe, add a webhook endpoint pointing to your RestroAgent webhook URL to receive payment events.' },
      { title: 'Test the Integration', description: 'Use Stripe test mode to process a test payment and verify the order appears in RestroAgent.' },
    ],
  },
  {
    id: 'paypal',
    name: 'PayPal',
    description: 'Enable PayPal checkout for customers who prefer to pay with their PayPal balance or linked cards.',
    category: 'Payment Gateways',
    logo: 'PP',
    logoColor: 'hsl(210, 80%, 35%)',
    connected: false,
    setupSteps: [
      { title: 'Create a PayPal Developer App', description: 'Go to developer.paypal.com, log in, and create a new app under My Apps & Credentials.' },
      { title: 'Get Client ID and Secret', description: 'Copy the Client ID and Secret from your app. Switch to Live mode for production credentials.' },
      { title: 'Enter Credentials', description: 'Paste your Client ID and Secret in the PayPal connection form in RestroAgent.' },
      { title: 'Set Return URLs', description: 'Configure the return and cancel URLs to point to your restaurant ordering page.' },
    ],
  },
  {
    id: 'doordash',
    name: 'DoorDash Drive',
    description: 'Dispatch delivery drivers on-demand through DoorDash Drive for your own online orders.',
    category: 'Delivery Platforms',
    logo: 'DD',
    logoColor: 'hsl(0, 80%, 50%)',
    connected: false,
    popular: true,
    setupSteps: [
      { title: 'Apply for DoorDash Drive Access', description: 'Visit developer.doordash.com and apply for Drive API access. Approval typically takes 2–3 business days.' },
      { title: 'Get API Key', description: 'Once approved, log in to the Developer Portal and generate an API key under your application settings.' },
      { title: 'Configure Delivery Zone', description: 'Set your restaurant address and maximum delivery radius. DoorDash will only dispatch drivers within this zone.' },
      { title: 'Connect to RestroAgent', description: 'Enter your API key and restaurant address in the DoorDash connection form.' },
      { title: 'Set Dispatch Rules', description: 'Configure when to auto-dispatch (e.g., when order is confirmed) and set estimated prep times.' },
    ],
  },
  {
    id: 'ubereats',
    name: 'Uber Eats',
    description: 'Sync your menu with Uber Eats and receive orders directly into your RestroAgent dashboard.',
    category: 'Delivery Platforms',
    logo: 'UE',
    logoColor: 'hsl(45, 100%, 40%)',
    connected: false,
    setupSteps: [
      { title: 'Join Uber Eats Restaurant Manager', description: 'Log in to restaurants.ubereats.com and navigate to Settings > Integrations.' },
      { title: 'Enable POS Integration', description: 'Select "POS Integration" and choose "Custom POS" from the list of providers.' },
      { title: 'Generate Store UUID', description: 'Copy your Store UUID from the integration settings page.' },
      { title: 'Connect via RestroAgent', description: 'Enter your Store UUID and Uber Eats API credentials in the connection form.' },
      { title: 'Sync Menu', description: 'Trigger an initial menu sync to push your RestroAgent menu to Uber Eats.' },
    ],
  },
  {
    id: 'hubspot',
    name: 'HubSpot CRM',
    description: 'Sync customer profiles, order history, and AI conversation data to HubSpot for marketing automation.',
    category: 'CRM Tools',
    logo: 'HS',
    logoColor: 'hsl(22, 89%, 48%)',
    connected: false,
    setupSteps: [
      { title: 'Create a HubSpot Private App', description: 'In HubSpot, go to Settings > Integrations > Private Apps and create a new app with CRM read/write scopes.' },
      { title: 'Copy Access Token', description: 'Copy the access token generated for your private app.' },
      { title: 'Connect to RestroAgent', description: 'Paste the access token in the HubSpot connection form.' },
      { title: 'Map Customer Fields', description: 'Map RestroAgent customer fields (name, email, phone, order count) to HubSpot contact properties.' },
      { title: 'Configure Sync Frequency', description: 'Choose real-time sync (via webhooks) or scheduled sync (hourly/daily).' },
    ],
  },
  {
    id: 'mailchimp',
    name: 'Mailchimp',
    description: 'Automatically add customers to Mailchimp lists and trigger email campaigns based on order behavior.',
    category: 'CRM Tools',
    logo: 'MC',
    logoColor: 'hsl(45, 100%, 35%)',
    connected: false,
    setupSteps: [
      { title: 'Get Mailchimp API Key', description: 'In Mailchimp, go to Account > Extras > API Keys and generate a new key.' },
      { title: 'Find Your Audience ID', description: 'Navigate to Audience > All Contacts > Settings > Audience name and defaults to find your Audience ID.' },
      { title: 'Connect in RestroAgent', description: 'Enter your API Key and Audience ID in the Mailchimp connection form.' },
      { title: 'Set Subscription Rules', description: 'Choose which customer actions trigger a Mailchimp subscription (e.g., first order, loyalty milestone).' },
    ],
  },
  {
    id: 'twilio',
    name: 'Twilio SMS',
    description: 'Send SMS notifications for order confirmations, booking reminders, and customer alerts via Twilio.',
    category: 'Messaging',
    logo: 'TW',
    logoColor: 'hsl(0, 70%, 45%)',
    connected: false,
    setupSteps: [
      { title: 'Create a Twilio Account', description: 'Sign up at twilio.com and verify your phone number.' },
      { title: 'Get Account SID and Auth Token', description: 'From the Twilio Console dashboard, copy your Account SID and Auth Token.' },
      { title: 'Purchase a Phone Number', description: 'Buy a Twilio phone number to use as the sender for SMS messages.' },
      { title: 'Connect to RestroAgent', description: 'Enter your Account SID, Auth Token, and Twilio phone number in the connection form.' },
    ],
  },
  {
    id: 'google-analytics',
    name: 'Google Analytics',
    description: 'Track customer journeys, conversion funnels, and AI agent performance in Google Analytics 4.',
    category: 'Analytics',
    logo: 'GA',
    logoColor: 'hsl(210, 100%, 40%)',
    connected: false,
    setupSteps: [
      { title: 'Create a GA4 Property', description: 'In Google Analytics, create a new GA4 property for your restaurant.' },
      { title: 'Get Measurement ID', description: 'Go to Admin > Data Streams > Web and copy your Measurement ID (G-XXXXXXXXXX).' },
      { title: 'Enter Measurement ID', description: 'Paste your Measurement ID in the Google Analytics connection form in RestroAgent.' },
      { title: 'Verify Data Flow', description: 'Use the GA4 DebugView to confirm events are being received from RestroAgent.' },
    ],
  },
];

const categories = ['All', 'POS Systems', 'Payment Gateways', 'Delivery Platforms', 'CRM Tools', 'Messaging', 'Analytics'];

const categoryIcons: Record<string, React.ReactNode> = {
  'POS Systems': <ShoppingCart size={14} />,
  'Payment Gateways': <CreditCard size={14} />,
  'Delivery Platforms': <Truck size={14} />,
  'CRM Tools': <Users size={14} />,
  'Messaging': <MessageSquare size={14} />,
  'Analytics': <BarChart3 size={14} />,
};

export default function MarketplacePage() {
  const { t } = useLanguage();
  usePageHeader(t('settings.marketplace.title', "Marketplace"), t('settings.marketplace.subtitle', "Discover and install integrations"));
  const [search, setSearch] = useState('');
  const [activeCategory, setActiveCategory] = useState('All');
  const [guideOpen, setGuideOpen] = useState<Integration | null>(null);
  const [expandedStep, setExpandedStep] = useState<number | null>(0);

  const filtered = integrations.filter((i) => {
    const matchSearch = i.name.toLowerCase().includes(search.toLowerCase()) || i.description.toLowerCase().includes(search.toLowerCase());
    const matchCat = activeCategory === 'All' || i.category === activeCategory;
    return matchSearch && matchCat;
  });

  const connectedCount = 0;

  return (
    <>
      <div className="flex h-full" style={{ backgroundColor: 'hsl(var(--background))' }}>
        {/* Main Content */}
        <div className={`flex-1 flex flex-col min-w-0 transition-all duration-300 ${guideOpen ? 'mr-0' : ''}`}>
          {/* Header */}
          <div className="px-6 pt-6 pb-4 shrink-0" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
            <div className="flex items-start justify-between gap-4 mb-4">
              <div>
                <h1 className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{t('settings.marketplace.title', 'Marketplace')}</h1>
                <p className="text-sm mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('settings.marketplace.connect_favorite', 'Connect your favourite tools and platforms to RestroAgent')}
                </p>
              </div>
              <div
                className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium"
                style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
              >
                <CheckCircle2 size={15} />
                {connectedCount} {t('settings.marketplace.connected', 'connected')}
              </div>
            </div>

            {/* Search + Category Filter */}
            <div className="flex flex-col sm:flex-row gap-3">
              <div className="relative flex-1 max-w-sm">
                <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <input
                  type="text"
                  placeholder={t('settings.marketplace.search_placeholder', "Search integrations...")}
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 text-sm rounded-lg border outline-none"
                  style={{
                    backgroundColor: 'hsl(var(--surface))',
                    borderColor: 'hsl(var(--border))',
                    color: 'hsl(var(--foreground))',
                  }}
                />
              </div>
              <div className="flex gap-1.5 flex-wrap">
                {categories.map((cat) => (
                  <button
                    key={cat}
                    onClick={() => setActiveCategory(cat)}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
                    style={
                      activeCategory === cat
                        ? { backgroundColor: 'hsl(var(--primary))', color: 'white' }
                        : { backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--foreground-secondary))', border: '1px solid hsl(var(--border))' }
                    }
                  >
                    {cat !== 'All' && categoryIcons[cat]}
                    {cat === 'All' ? t('settings.marketplace.category_all', 'All') : t(`settings.marketplace.category_${cat.toLowerCase().replace(/\s+/g, '_')}`, cat)}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Grid */}
          <div className="flex-1 overflow-y-auto p-6">
            {filtered.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-20 text-center">
                <Zap size={40} style={{ color: 'hsl(var(--muted-foreground))' }} className="mb-3 opacity-40" />
                <p className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('settings.marketplace.no_integrations', 'No integrations found')}</p>
                <p className="text-sm mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('settings.marketplace.try_different_search', 'Try a different search or category')}</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {filtered.map((integration) => (
                    <div
                      key={integration.id}
                      className="rounded-xl p-5 flex flex-col gap-4 relative"
                      style={{
                        backgroundColor: 'hsl(var(--surface))',
                        border: '1px solid hsl(var(--border))',
                      }}
                    >
                      {integration.popular && (
                        <span
                          className="absolute top-3 right-3 flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full"
                          style={{ backgroundColor: 'hsl(45, 100%, 90%)', color: 'hsl(45, 100%, 30%)' }}
                        >
                          <Star size={10} fill="currentColor" /> {t('settings.marketplace.popular', 'Popular')}
                        </span>
                      )}

                      <div className="flex items-center gap-3">
                        <div
                          className="w-11 h-11 rounded-xl flex items-center justify-center text-white text-sm font-bold shrink-0"
                          style={{ backgroundColor: integration.logoColor }}
                        >
                          {integration.logo}
                        </div>
                        <div className="min-w-0">
                          <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{integration.name}</p>
                          <span
                            className="text-xs px-2 py-0.5 rounded-full font-medium"
                            style={{ backgroundColor: 'hsl(var(--background))', color: 'hsl(var(--muted-foreground))' }}
                          >
                            {t(`settings.marketplace.category_${integration.category.toLowerCase().replace(/\s+/g, '_')}`, integration.category)}
                          </span>
                        </div>
                      </div>

                      <p className="text-xs leading-relaxed flex-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t(`settings.marketplace.desc_${integration.id}`, integration.description)}
                      </p>

                      <div className="flex items-center gap-1.5 text-xs font-medium">
                        <Circle size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
                        <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('settings.marketplace.not_connected', 'Not connected')}</span>
                      </div>

                      <div className="flex gap-2">
                        <button
                          onClick={() => { setGuideOpen(integration); setExpandedStep(0); }}
                          className="flex-1 py-1.5 rounded-lg text-xs font-semibold text-white transition-all hover:opacity-90"
                          style={{ backgroundColor: 'hsl(var(--primary))' }}
                        >
                          {t('settings.marketplace.setup_guide_btn', 'Setup Guide')}
                        </button>
                        <button
                          onClick={() => { setGuideOpen(integration); setExpandedStep(0); }}
                          className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium border transition-all hover:opacity-80"
                          style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}
                        >
                          <BookOpen size={12} />
                          {t('settings.marketplace.guide', 'Guide')}
                        </button>
                      </div>
                    </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Setup Guide Side Panel */}
        {guideOpen && (
          <div
            className="shrink-0 flex flex-col"
            style={{
              width: '360px',
              borderLeft: '1px solid hsl(var(--border))',
              backgroundColor: 'hsl(var(--surface))',
            }}
          >
            {/* Panel Header */}
            <div className="flex items-center justify-between px-5 py-4 shrink-0" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
              <div className="flex items-center gap-3">
                <div
                  className="w-9 h-9 rounded-lg flex items-center justify-center text-white text-xs font-bold"
                  style={{ backgroundColor: guideOpen.logoColor }}
                >
                  {guideOpen.logo}
                </div>
                <div>
                  <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{guideOpen.name}</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('settings.marketplace.setup_guide', 'Setup Guide')}</p>
                </div>
              </div>
              <button
                onClick={() => setGuideOpen(null)}
                className="p-1.5 rounded-lg transition-colors hover:opacity-70"
                style={{ color: 'hsl(var(--muted-foreground))' }}
              >
                <X size={16} />
              </button>
            </div>

            {/* Steps */}
            <div className="flex-1 overflow-y-auto p-5 space-y-3">
              <p className="text-xs font-semibold uppercase tracking-wider mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {t('settings.marketplace.step_by_step', 'Step-by-step instructions')}
              </p>
              {guideOpen.setupSteps.map((step, idx) => (
                <div
                  key={idx}
                  className="rounded-xl overflow-hidden"
                  style={{ border: '1px solid hsl(var(--border))' }}
                >
                  <button
                    className="w-full flex items-center gap-3 px-4 py-3 text-left transition-colors"
                    style={{
                      backgroundColor: expandedStep === idx ? 'hsl(var(--primary-light))' : 'transparent',
                    }}
                    onClick={() => setExpandedStep(expandedStep === idx ? null : idx)}
                  >
                    <span
                      className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold shrink-0"
                      style={{
                        backgroundColor: expandedStep === idx ? 'hsl(var(--primary))' : 'hsl(var(--background))',
                        color: expandedStep === idx ? 'white' : 'hsl(var(--muted-foreground))',
                      }}
                    >
                      {idx + 1}
                    </span>
                    <span className="flex-1 text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t(`settings.marketplace.step_title_${guideOpen.id}_${idx}`, step.title)}</span>
                    <ChevronDown
                      size={14}
                      className="shrink-0 transition-transform"
                      style={{
                        color: 'hsl(var(--muted-foreground))',
                        transform: expandedStep === idx ? 'rotate(180deg)' : 'rotate(0deg)',
                      }}
                    />
                  </button>
                  {expandedStep === idx && (
                    <div className="px-4 pb-4 pt-1">
                      <p className="text-xs leading-relaxed" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t(`settings.marketplace.step_desc_${guideOpen.id}_${idx}`, step.description)}
                      </p>
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* Panel Footer */}
            <div className="px-5 py-4 shrink-0 space-y-2" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <div
                className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-semibold"
                style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}
              >
                <Circle size={15} />
                {t('common.coming_soon', 'Coming Soon')}
              </div>
              {guideOpen.docsUrl && (
                <a
                  href={guideOpen.docsUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-full flex items-center justify-center gap-2 py-2 rounded-xl text-xs font-medium border transition-all hover:opacity-80"
                  style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}
                >
                  <ExternalLink size={12} />
                  {t('settings.marketplace.official_docs', 'Official Documentation')}
                </a>
              )}
            </div>
          </div>
        )}
      </div>
    </>
  );
}
