/**
 * Stripe Settings Panel Component
 *
 * Comprehensive settings panel for Stripe Connect accounts.
 * Allows tenants to configure payout schedules, business profile,
 * branding, and view bank accounts.
 */

import React, { useState, useEffect } from 'react';
import {
  Calendar,
  Building2,
  Palette,
  Landmark,
  Loader2,
  AlertCircle,
  CheckCircle,
  ExternalLink,
  Save,
  RefreshCw,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useStripeSettings, useUpdateStripeSettings, useCreateConnectLoginLink } from '../hooks/usePayments';
import type {
  PayoutInterval,
  WeeklyAnchor,
  StripeSettingsUpdate,
} from '../api/payments';

interface StripeSettingsPanelProps {
  stripeAccountId: string;
}

type TabId = 'payouts' | 'business' | 'branding' | 'bank';

const StripeSettingsPanel: React.FC<StripeSettingsPanelProps> = ({ stripeAccountId }) => {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabId>('payouts');
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const { data: settings, isLoading, error, refetch } = useStripeSettings();
  const updateMutation = useUpdateStripeSettings();
  const loginLinkMutation = useCreateConnectLoginLink();

  // Clear success message after 3 seconds
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(null), 3000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  // Handle opening Stripe Dashboard
  const handleOpenStripeDashboard = async () => {
    try {
      // Pass the current page URL as return/refresh URLs for Custom accounts
      const currentUrl = window.location.href;
      const result = await loginLinkMutation.mutateAsync({
        return_url: currentUrl,
        refresh_url: currentUrl,
      });

      if (result.type === 'login_link') {
        // Express accounts: Open dashboard in new tab (user stays there)
        window.open(result.url, '_blank');
      } else {
        // Custom accounts: Navigate in same window (redirects back when done)
        window.location.href = result.url;
      }
    } catch {
      // Error is shown via mutation state
    }
  };

  const tabs = [
    { id: 'payouts' as TabId, label: t('payments.stripeSettings.payouts'), icon: Calendar },
    { id: 'business' as TabId, label: t('payments.stripeSettings.businessProfile'), icon: Building2 },
    { id: 'branding' as TabId, label: t('payments.stripeSettings.branding'), icon: Palette },
    { id: 'bank' as TabId, label: t('payments.stripeSettings.bankAccounts'), icon: Landmark },
  ];

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="animate-spin text-brand-500 mr-3" size={24} />
        <span className="text-gray-600 dark:text-gray-400">{t('payments.stripeSettings.loading')}</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <AlertCircle className="text-red-600 dark:text-red-400 shrink-0 mt-0.5" size={20} />
          <div className="flex-1">
            <h4 className="font-medium text-red-800 dark:text-red-300">{t('payments.stripeSettings.loadError')}</h4>
            <p className="text-sm text-red-700 dark:text-red-400 mt-1">
              {error instanceof Error ? error.message : t('payments.stripeSettings.unknownError')}
            </p>
            <button
              onClick={() => refetch()}
              className="mt-3 flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 bg-red-100 dark:bg-red-900/30 rounded-lg hover:bg-red-200 dark:hover:bg-red-900/50"
            >
              <RefreshCw size={14} />
              {t('common.retry')}
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (!settings) {
    return null;
  }

  const handleSave = async (updates: StripeSettingsUpdate) => {
    try {
      await updateMutation.mutateAsync(updates);
      setSuccessMessage(t('payments.stripeSettings.savedSuccessfully'));
    } catch {
      // Error is handled by mutation state
    }
  };

  // For sub-tab links that need the static URL structure
  const stripeDashboardUrl = `https://dashboard.stripe.com/${stripeAccountId.startsWith('acct_') ? stripeAccountId : ''}`;

  return (
    <div className="space-y-6">
      {/* Header with Stripe Dashboard link */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            {t('payments.stripeSettings.title')}
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t('payments.stripeSettings.description')}
          </p>
        </div>
        <button
          onClick={handleOpenStripeDashboard}
          disabled={loginLinkMutation.isPending}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-brand-600 dark:text-brand-400 bg-brand-50 dark:bg-brand-900/20 rounded-lg hover:bg-brand-100 dark:hover:bg-brand-900/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loginLinkMutation.isPending ? (
            <Loader2 className="animate-spin" size={16} />
          ) : (
            <ExternalLink size={16} />
          )}
          {t('payments.stripeSettings.stripeDashboard')}
        </button>
      </div>

      {/* Login link error */}
      {loginLinkMutation.isError && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
          <div className="flex items-center gap-2 text-red-700 dark:text-red-300">
            <AlertCircle size={16} />
            <span className="text-sm font-medium">
              {loginLinkMutation.error instanceof Error
                ? loginLinkMutation.error.message
                : t('payments.stripeSettings.loginLinkError')}
            </span>
          </div>
        </div>
      )}

      {/* Success message */}
      {successMessage && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
          <div className="flex items-center gap-2 text-green-700 dark:text-green-300">
            <CheckCircle size={16} />
            <span className="text-sm font-medium">{successMessage}</span>
          </div>
        </div>
      )}

      {/* Error message */}
      {updateMutation.isError && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
          <div className="flex items-center gap-2 text-red-700 dark:text-red-300">
            <AlertCircle size={16} />
            <span className="text-sm font-medium">
              {updateMutation.error instanceof Error
                ? updateMutation.error.message
                : t('payments.stripeSettings.saveError')}
            </span>
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="flex -mb-px space-x-6">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-1 py-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-brand-500 text-brand-600 dark:text-brand-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
              }`}
            >
              <tab.icon size={16} />
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab content */}
      <div className="min-h-[300px]">
        {activeTab === 'payouts' && (
          <PayoutsTab
            settings={settings.payouts}
            onSave={handleSave}
            isSaving={updateMutation.isPending}
          />
        )}
        {activeTab === 'business' && (
          <BusinessProfileTab
            settings={settings.business_profile}
            onSave={handleSave}
            isSaving={updateMutation.isPending}
          />
        )}
        {activeTab === 'branding' && (
          <BrandingTab
            settings={settings.branding}
            onSave={handleSave}
            isSaving={updateMutation.isPending}
            stripeDashboardUrl={stripeDashboardUrl}
          />
        )}
        {activeTab === 'bank' && (
          <BankAccountsTab
            accounts={settings.bank_accounts}
            stripeDashboardUrl={stripeDashboardUrl}
          />
        )}
      </div>
    </div>
  );
};

// ============================================================================
// Payouts Tab
// ============================================================================

interface PayoutsTabProps {
  settings: {
    schedule: {
      interval: PayoutInterval;
      delay_days: number;
      weekly_anchor: WeeklyAnchor | null;
      monthly_anchor: number | null;
    };
    statement_descriptor: string;
  };
  onSave: (updates: StripeSettingsUpdate) => Promise<void>;
  isSaving: boolean;
}

const PayoutsTab: React.FC<PayoutsTabProps> = ({ settings, onSave, isSaving }) => {
  const { t } = useTranslation();
  const [interval, setInterval] = useState<PayoutInterval>(settings.schedule.interval);
  const [delayDays, setDelayDays] = useState(settings.schedule.delay_days);
  const [weeklyAnchor, setWeeklyAnchor] = useState<WeeklyAnchor | null>(settings.schedule.weekly_anchor);
  const [monthlyAnchor, setMonthlyAnchor] = useState<number | null>(settings.schedule.monthly_anchor);
  const [statementDescriptor, setStatementDescriptor] = useState(settings.statement_descriptor);
  const [descriptorError, setDescriptorError] = useState<string | null>(null);

  const weekDays: WeeklyAnchor[] = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

  const validateDescriptor = (value: string) => {
    if (value.length > 22) {
      setDescriptorError(t('payments.stripeSettings.descriptorTooLong'));
      return false;
    }
    if (value && !/^[a-zA-Z0-9\s.\-]+$/.test(value)) {
      setDescriptorError(t('payments.stripeSettings.descriptorInvalidChars'));
      return false;
    }
    setDescriptorError(null);
    return true;
  };

  const handleSave = async () => {
    if (!validateDescriptor(statementDescriptor)) return;

    const updates: StripeSettingsUpdate = {
      payouts: {
        schedule: {
          interval,
          delay_days: delayDays,
          ...(interval === 'weekly' && weeklyAnchor ? { weekly_anchor: weeklyAnchor } : {}),
          ...(interval === 'monthly' && monthlyAnchor ? { monthly_anchor: monthlyAnchor } : {}),
        },
        ...(statementDescriptor ? { statement_descriptor: statementDescriptor } : {}),
      },
    };
    await onSave(updates);
  };

  return (
    <div className="space-y-6">
      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <p className="text-sm text-blue-700 dark:text-blue-300">
          {t('payments.stripeSettings.payoutsDescription')}
        </p>
      </div>

      {/* Payout Schedule */}
      <div className="space-y-4">
        <h4 className="font-medium text-gray-900 dark:text-white">{t('payments.stripeSettings.payoutSchedule')}</h4>

        {/* Interval */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.payoutInterval')}
          </label>
          <select
            value={interval}
            onChange={(e) => setInterval(e.target.value as PayoutInterval)}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          >
            <option value="daily">{t('payments.stripeSettings.intervalDaily')}</option>
            <option value="weekly">{t('payments.stripeSettings.intervalWeekly')}</option>
            <option value="monthly">{t('payments.stripeSettings.intervalMonthly')}</option>
            <option value="manual">{t('payments.stripeSettings.intervalManual')}</option>
          </select>
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
            {t('payments.stripeSettings.intervalHint')}
          </p>
        </div>

        {/* Delay Days */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.delayDays')}
          </label>
          <select
            value={delayDays}
            onChange={(e) => setDelayDays(Number(e.target.value))}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          >
            {[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].map((days) => (
              <option key={days} value={days}>
                {days} {t('payments.stripeSettings.days')}
              </option>
            ))}
          </select>
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
            {t('payments.stripeSettings.delayDaysHint')}
          </p>
        </div>

        {/* Weekly Anchor */}
        {interval === 'weekly' && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('payments.stripeSettings.weeklyAnchor')}
            </label>
            <select
              value={weeklyAnchor || 'monday'}
              onChange={(e) => setWeeklyAnchor(e.target.value as WeeklyAnchor)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
            >
              {weekDays.map((day) => (
                <option key={day} value={day}>
                  {t(`payments.stripeSettings.${day}`)}
                </option>
              ))}
            </select>
          </div>
        )}

        {/* Monthly Anchor */}
        {interval === 'monthly' && (
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('payments.stripeSettings.monthlyAnchor')}
            </label>
            <select
              value={monthlyAnchor || 1}
              onChange={(e) => setMonthlyAnchor(Number(e.target.value))}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
            >
              {Array.from({ length: 31 }, (_, i) => i + 1).map((day) => (
                <option key={day} value={day}>
                  {t('payments.stripeSettings.dayOfMonth', { day })}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Statement Descriptor */}
      <div>
        <h4 className="font-medium text-gray-900 dark:text-white mb-4">{t('payments.stripeSettings.statementDescriptor')}</h4>
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.descriptorLabel')}
          </label>
          <input
            type="text"
            value={statementDescriptor}
            onChange={(e) => {
              setStatementDescriptor(e.target.value);
              validateDescriptor(e.target.value);
            }}
            maxLength={22}
            placeholder={t('payments.stripeSettings.descriptorPlaceholder')}
            className={`w-full px-3 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent ${
              descriptorError ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
            }`}
          />
          {descriptorError ? (
            <p className="mt-1 text-xs text-red-500">{descriptorError}</p>
          ) : (
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              {t('payments.stripeSettings.descriptorHint')} ({statementDescriptor.length}/22)
            </p>
          )}
        </div>
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
          onClick={handleSave}
          disabled={isSaving || !!descriptorError}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSaving ? (
            <Loader2 className="animate-spin" size={16} />
          ) : (
            <Save size={16} />
          )}
          {t('common.save')}
        </button>
      </div>
    </div>
  );
};

// ============================================================================
// Business Profile Tab
// ============================================================================

interface BusinessProfileTabProps {
  settings: {
    name: string;
    support_email: string;
    support_phone: string;
    support_url: string;
  };
  onSave: (updates: StripeSettingsUpdate) => Promise<void>;
  isSaving: boolean;
}

const BusinessProfileTab: React.FC<BusinessProfileTabProps> = ({ settings, onSave, isSaving }) => {
  const { t } = useTranslation();
  const [name, setName] = useState(settings.name);
  const [supportEmail, setSupportEmail] = useState(settings.support_email);
  const [supportPhone, setSupportPhone] = useState(settings.support_phone);
  const [supportUrl, setSupportUrl] = useState(settings.support_url);

  const handleSave = async () => {
    const updates: StripeSettingsUpdate = {
      business_profile: {
        name,
        support_email: supportEmail,
        support_phone: supportPhone,
        support_url: supportUrl,
      },
    };
    await onSave(updates);
  };

  return (
    <div className="space-y-6">
      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <p className="text-sm text-blue-700 dark:text-blue-300">
          {t('payments.stripeSettings.businessProfileDescription')}
        </p>
      </div>

      <div className="grid gap-4">
        {/* Business Name */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.businessName')}
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          />
        </div>

        {/* Support Email */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.supportEmail')}
          </label>
          <input
            type="email"
            value={supportEmail}
            onChange={(e) => setSupportEmail(e.target.value)}
            placeholder="support@yourbusiness.com"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          />
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
            {t('payments.stripeSettings.supportEmailHint')}
          </p>
        </div>

        {/* Support Phone */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.supportPhone')}
          </label>
          <input
            type="tel"
            value={supportPhone}
            onChange={(e) => setSupportPhone(e.target.value)}
            placeholder="+1 (555) 123-4567"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          />
        </div>

        {/* Support URL */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.supportUrl')}
          </label>
          <input
            type="url"
            value={supportUrl}
            onChange={(e) => setSupportUrl(e.target.value)}
            placeholder="https://yourbusiness.com/support"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
          />
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
            {t('payments.stripeSettings.supportUrlHint')}
          </p>
        </div>
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
          onClick={handleSave}
          disabled={isSaving}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSaving ? (
            <Loader2 className="animate-spin" size={16} />
          ) : (
            <Save size={16} />
          )}
          {t('common.save')}
        </button>
      </div>
    </div>
  );
};

// ============================================================================
// Branding Tab
// ============================================================================

interface BrandingTabProps {
  settings: {
    primary_color: string;
    secondary_color: string;
    icon: string;
    logo: string;
  };
  onSave: (updates: StripeSettingsUpdate) => Promise<void>;
  isSaving: boolean;
  stripeDashboardUrl: string;
}

const BrandingTab: React.FC<BrandingTabProps> = ({ settings, onSave, isSaving, stripeDashboardUrl }) => {
  const { t } = useTranslation();
  const [primaryColor, setPrimaryColor] = useState(settings.primary_color || '#3b82f6');
  const [secondaryColor, setSecondaryColor] = useState(settings.secondary_color || '#10b981');
  const [colorError, setColorError] = useState<string | null>(null);

  const validateColor = (color: string): boolean => {
    if (!color) return true;
    return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color);
  };

  const handleSave = async () => {
    if (primaryColor && !validateColor(primaryColor)) {
      setColorError(t('payments.stripeSettings.invalidColorFormat'));
      return;
    }
    if (secondaryColor && !validateColor(secondaryColor)) {
      setColorError(t('payments.stripeSettings.invalidColorFormat'));
      return;
    }
    setColorError(null);

    const updates: StripeSettingsUpdate = {
      branding: {
        primary_color: primaryColor,
        secondary_color: secondaryColor,
      },
    };
    await onSave(updates);
  };

  return (
    <div className="space-y-6">
      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <p className="text-sm text-blue-700 dark:text-blue-300">
          {t('payments.stripeSettings.brandingDescription')}
        </p>
      </div>

      {colorError && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
          <p className="text-sm text-red-700 dark:text-red-300">{colorError}</p>
        </div>
      )}

      <div className="grid gap-6 sm:grid-cols-2">
        {/* Primary Color */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.primaryColor')}
          </label>
          <div className="flex items-center gap-3">
            <input
              type="color"
              value={primaryColor || '#3b82f6'}
              onChange={(e) => setPrimaryColor(e.target.value)}
              className="h-10 w-14 rounded border border-gray-300 dark:border-gray-600 cursor-pointer"
            />
            <input
              type="text"
              value={primaryColor}
              onChange={(e) => setPrimaryColor(e.target.value)}
              placeholder="#3b82f6"
              className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
            />
          </div>
        </div>

        {/* Secondary Color */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            {t('payments.stripeSettings.secondaryColor')}
          </label>
          <div className="flex items-center gap-3">
            <input
              type="color"
              value={secondaryColor || '#10b981'}
              onChange={(e) => setSecondaryColor(e.target.value)}
              className="h-10 w-14 rounded border border-gray-300 dark:border-gray-600 cursor-pointer"
            />
            <input
              type="text"
              value={secondaryColor}
              onChange={(e) => setSecondaryColor(e.target.value)}
              placeholder="#10b981"
              className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
            />
          </div>
        </div>
      </div>

      {/* Logo & Icon Info */}
      <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
        <h4 className="font-medium text-gray-900 dark:text-white mb-2">{t('payments.stripeSettings.logoAndIcon')}</h4>
        <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
          {t('payments.stripeSettings.logoAndIconDescription')}
        </p>
        <a
          href={`${stripeDashboardUrl}/settings/branding`}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 text-sm font-medium text-brand-600 dark:text-brand-400 hover:underline"
        >
          <ExternalLink size={14} />
          {t('payments.stripeSettings.uploadInStripeDashboard')}
        </a>

        {/* Display current logo/icon if set */}
        {(settings.icon || settings.logo) && (
          <div className="flex items-center gap-4 mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
            {settings.icon && (
              <div className="text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('payments.stripeSettings.icon')}</p>
                <div className="w-12 h-12 bg-gray-200 dark:bg-gray-600 rounded flex items-center justify-center">
                  <CheckCircle className="text-green-500" size={20} />
                </div>
              </div>
            )}
            {settings.logo && (
              <div className="text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">{t('payments.stripeSettings.logo')}</p>
                <div className="w-24 h-12 bg-gray-200 dark:bg-gray-600 rounded flex items-center justify-center">
                  <CheckCircle className="text-green-500" size={20} />
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Save Button */}
      <div className="flex justify-end pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
          onClick={handleSave}
          disabled={isSaving}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSaving ? (
            <Loader2 className="animate-spin" size={16} />
          ) : (
            <Save size={16} />
          )}
          {t('common.save')}
        </button>
      </div>
    </div>
  );
};

// ============================================================================
// Bank Accounts Tab
// ============================================================================

interface BankAccountsTabProps {
  accounts: Array<{
    id: string;
    bank_name: string;
    last4: string;
    currency: string;
    default_for_currency: boolean;
    status: string;
  }>;
  stripeDashboardUrl: string;
}

const BankAccountsTab: React.FC<BankAccountsTabProps> = ({ accounts, stripeDashboardUrl }) => {
  const { t } = useTranslation();

  return (
    <div className="space-y-6">
      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <p className="text-sm text-blue-700 dark:text-blue-300">
          {t('payments.stripeSettings.bankAccountsDescription')}
        </p>
      </div>

      {accounts.length === 0 ? (
        <div className="text-center py-8">
          <Landmark className="mx-auto text-gray-400 mb-3" size={40} />
          <h4 className="font-medium text-gray-900 dark:text-white mb-1">
            {t('payments.stripeSettings.noBankAccounts')}
          </h4>
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
            {t('payments.stripeSettings.noBankAccountsDescription')}
          </p>
          <a
            href={`${stripeDashboardUrl}/settings/payouts`}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-500 rounded-lg hover:bg-brand-600"
          >
            <ExternalLink size={16} />
            {t('payments.stripeSettings.addInStripeDashboard')}
          </a>
        </div>
      ) : (
        <div className="space-y-3">
          {accounts.map((account) => (
            <div
              key={account.id}
              className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
            >
              <div className="flex items-center gap-4">
                <div className="p-2 bg-white dark:bg-gray-600 rounded-lg">
                  <Landmark className="text-gray-600 dark:text-gray-300" size={20} />
                </div>
                <div>
                  <p className="font-medium text-gray-900 dark:text-white">
                    {account.bank_name || t('payments.stripeSettings.bankAccount')}
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    ••••{account.last4} · {account.currency.toUpperCase()}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                {account.default_for_currency && (
                  <span className="px-2 py-1 text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 rounded-full">
                    {t('payments.stripeSettings.default')}
                  </span>
                )}
                <span
                  className={`px-2 py-1 text-xs font-medium rounded-full ${
                    account.status === 'verified'
                      ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300'
                      : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300'
                  }`}
                >
                  {account.status}
                </span>
              </div>
            </div>
          ))}

          <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
            <a
              href={`${stripeDashboardUrl}/settings/payouts`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 text-sm font-medium text-brand-600 dark:text-brand-400 hover:underline"
            >
              <ExternalLink size={14} />
              {t('payments.stripeSettings.manageInStripeDashboard')}
            </a>
          </div>
        </div>
      )}
    </div>
  );
};

export default StripeSettingsPanel;
