/**
 * AccountSettingsPanel Component
 * Account-level configuration for investment accounts
 * OQI-004: Cuentas de Inversion
 */

import React, { useState } from 'react';
import {
  Settings,
  Bell,
  RefreshCw,
  Calendar,
  Shield,
  DollarSign,
  AlertTriangle,
  CheckCircle,
  Info,
  ChevronRight,
  Save,
  X,
  TrendingUp,
} from 'lucide-react';

// ============================================================================
// Types
// ============================================================================

export interface AccountSettings {
  distributionFrequency: 'weekly' | 'biweekly' | 'monthly' | 'quarterly';
  autoReinvest: boolean;
  reinvestPercentage: number;
  notifications: {
    distributionAlert: boolean;
    performanceAlert: boolean;
    riskAlert: boolean;
    newsAlert: boolean;
  };
  riskAlerts: {
    enabled: boolean;
    drawdownThreshold: number;
    dailyLossThreshold: number;
  };
  withdrawalSettings: {
    preferredMethod: 'bank' | 'crypto' | 'wallet';
    autoWithdraw: boolean;
    autoWithdrawThreshold: number;
  };
}

export interface AccountForSettings {
  id: string;
  accountNumber: string;
  productName: string;
  currentBalance: number;
}

interface AccountSettingsPanelProps {
  account: AccountForSettings;
  settings: AccountSettings;
  onSave?: (settings: AccountSettings) => void;
  onCancel?: () => void;
  isLoading?: boolean;
  compact?: boolean;
}

// ============================================================================
// Sub-Components
// ============================================================================

interface ToggleSwitchProps {
  enabled: boolean;
  onChange: (value: boolean) => void;
  disabled?: boolean;
}

const ToggleSwitch: React.FC<ToggleSwitchProps> = ({ enabled, onChange, disabled = false }) => (
  <button
    type="button"
    onClick={() => !disabled && onChange(!enabled)}
    disabled={disabled}
    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
      enabled ? 'bg-emerald-500' : 'bg-slate-600'
    } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
  >
    <span
      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
        enabled ? 'translate-x-6' : 'translate-x-1'
      }`}
    />
  </button>
);

interface SettingRowProps {
  icon: React.ReactNode;
  label: string;
  description?: string;
  children: React.ReactNode;
}

const SettingRow: React.FC<SettingRowProps> = ({ icon, label, description, children }) => (
  <div className="flex items-center justify-between py-4 border-b border-slate-700/50 last:border-b-0">
    <div className="flex items-start gap-3">
      <div className="p-2 bg-slate-700/50 rounded-lg text-slate-400">{icon}</div>
      <div>
        <div className="font-medium text-white">{label}</div>
        {description && <div className="text-sm text-slate-500 mt-0.5">{description}</div>}
      </div>
    </div>
    <div>{children}</div>
  </div>
);

// ============================================================================
// Component
// ============================================================================

export const AccountSettingsPanel: React.FC<AccountSettingsPanelProps> = ({
  account,
  settings: initialSettings,
  onSave,
  onCancel,
  isLoading = false,
  compact = false,
}) => {
  const [settings, setSettings] = useState<AccountSettings>(initialSettings);
  const [activeSection, setActiveSection] = useState<string>('distribution');
  const [hasChanges, setHasChanges] = useState(false);

  const updateSettings = <K extends keyof AccountSettings>(
    key: K,
    value: AccountSettings[K]
  ) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
    setHasChanges(true);
  };

  const updateNestedSettings = <K extends keyof AccountSettings>(
    key: K,
    nestedKey: string,
    value: unknown
  ) => {
    setSettings((prev) => ({
      ...prev,
      [key]: { ...(prev[key] as Record<string, unknown>), [nestedKey]: value },
    }));
    setHasChanges(true);
  };

  const handleSave = () => {
    onSave?.(settings);
    setHasChanges(false);
  };

  const sections = [
    { id: 'distribution', label: 'Distribution', icon: Calendar },
    { id: 'reinvest', label: 'Auto-Reinvest', icon: RefreshCw },
    { id: 'notifications', label: 'Notifications', icon: Bell },
    { id: 'risk', label: 'Risk Alerts', icon: Shield },
    { id: 'withdrawal', label: 'Withdrawal', icon: DollarSign },
  ];

  if (compact) {
    return (
      <div className="bg-slate-800/50 rounded-xl border border-slate-700 p-4">
        <div className="flex items-center gap-3 mb-4">
          <div className="p-2 bg-slate-700 rounded-lg">
            <Settings className="w-5 h-5 text-slate-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Account Settings</h3>
            <p className="text-xs text-slate-500">{account.accountNumber}</p>
          </div>
        </div>

        <div className="space-y-3">
          {sections.map((section) => {
            const Icon = section.icon;
            return (
              <button
                key={section.id}
                onClick={() => setActiveSection(section.id)}
                className="w-full flex items-center justify-between p-3 bg-slate-900/50 rounded-lg hover:bg-slate-700/50 transition-colors"
              >
                <div className="flex items-center gap-2">
                  <Icon className="w-4 h-4 text-slate-400" />
                  <span className="text-sm text-white">{section.label}</span>
                </div>
                <ChevronRight className="w-4 h-4 text-slate-500" />
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  return (
    <div className="bg-slate-800/50 rounded-xl border border-slate-700 overflow-hidden">
      {/* Header */}
      <div className="p-5 border-b border-slate-700">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-slate-700 rounded-lg">
              <Settings className="w-5 h-5 text-slate-400" />
            </div>
            <div>
              <h3 className="font-semibold text-white text-lg">Account Settings</h3>
              <p className="text-sm text-slate-500">
                {account.productName} • {account.accountNumber}
              </p>
            </div>
          </div>
          {hasChanges && (
            <span className="px-2 py-1 bg-amber-500/20 text-amber-400 text-xs rounded">
              Unsaved Changes
            </span>
          )}
        </div>
      </div>

      {/* Navigation Tabs */}
      <div className="flex border-b border-slate-700 overflow-x-auto">
        {sections.map((section) => {
          const Icon = section.icon;
          const isActive = activeSection === section.id;

          return (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id)}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                isActive
                  ? 'border-blue-500 text-blue-400'
                  : 'border-transparent text-slate-400 hover:text-white'
              }`}
            >
              <Icon className="w-4 h-4" />
              {section.label}
            </button>
          );
        })}
      </div>

      {/* Content */}
      <div className="p-5">
        {/* Distribution Settings */}
        {activeSection === 'distribution' && (
          <div className="space-y-1">
            <SettingRow
              icon={<Calendar className="w-4 h-4" />}
              label="Distribution Frequency"
              description="How often you receive profit distributions"
            >
              <select
                value={settings.distributionFrequency}
                onChange={(e) =>
                  updateSettings('distributionFrequency', e.target.value as AccountSettings['distributionFrequency'])
                }
                className="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="weekly">Weekly</option>
                <option value="biweekly">Bi-weekly</option>
                <option value="monthly">Monthly</option>
                <option value="quarterly">Quarterly</option>
              </select>
            </SettingRow>

            <div className="mt-4 p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg">
              <div className="flex items-start gap-2">
                <Info className="w-4 h-4 text-blue-400 mt-0.5" />
                <p className="text-sm text-blue-300">
                  Distributions are processed on the last business day of each period.
                  Changes take effect from the next distribution cycle.
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Auto-Reinvest Settings */}
        {activeSection === 'reinvest' && (
          <div className="space-y-1">
            <SettingRow
              icon={<RefreshCw className="w-4 h-4" />}
              label="Auto-Reinvest Profits"
              description="Automatically reinvest your distributions"
            >
              <ToggleSwitch
                enabled={settings.autoReinvest}
                onChange={(value) => updateSettings('autoReinvest', value)}
              />
            </SettingRow>

            {settings.autoReinvest && (
              <SettingRow
                icon={<DollarSign className="w-4 h-4" />}
                label="Reinvest Percentage"
                description="Percentage of profits to reinvest"
              >
                <div className="flex items-center gap-2">
                  <input
                    type="range"
                    min="0"
                    max="100"
                    step="5"
                    value={settings.reinvestPercentage}
                    onChange={(e) => updateSettings('reinvestPercentage', parseInt(e.target.value))}
                    className="w-24"
                  />
                  <span className="text-white font-medium w-12 text-right">
                    {settings.reinvestPercentage}%
                  </span>
                </div>
              </SettingRow>
            )}
          </div>
        )}

        {/* Notifications Settings */}
        {activeSection === 'notifications' && (
          <div className="space-y-1">
            <SettingRow
              icon={<DollarSign className="w-4 h-4" />}
              label="Distribution Alerts"
              description="Get notified when distributions are processed"
            >
              <ToggleSwitch
                enabled={settings.notifications.distributionAlert}
                onChange={(value) => updateNestedSettings('notifications', 'distributionAlert', value)}
              />
            </SettingRow>

            <SettingRow
              icon={<TrendingUp className="w-4 h-4" />}
              label="Performance Alerts"
              description="Weekly performance summary notifications"
            >
              <ToggleSwitch
                enabled={settings.notifications.performanceAlert}
                onChange={(value) => updateNestedSettings('notifications', 'performanceAlert', value)}
              />
            </SettingRow>

            <SettingRow
              icon={<AlertTriangle className="w-4 h-4" />}
              label="Risk Alerts"
              description="Get notified about significant drawdowns"
            >
              <ToggleSwitch
                enabled={settings.notifications.riskAlert}
                onChange={(value) => updateNestedSettings('notifications', 'riskAlert', value)}
              />
            </SettingRow>

            <SettingRow
              icon={<Bell className="w-4 h-4" />}
              label="News & Updates"
              description="Product updates and market news"
            >
              <ToggleSwitch
                enabled={settings.notifications.newsAlert}
                onChange={(value) => updateNestedSettings('notifications', 'newsAlert', value)}
              />
            </SettingRow>
          </div>
        )}

        {/* Risk Alerts Settings */}
        {activeSection === 'risk' && (
          <div className="space-y-1">
            <SettingRow
              icon={<Shield className="w-4 h-4" />}
              label="Enable Risk Alerts"
              description="Receive alerts when thresholds are breached"
            >
              <ToggleSwitch
                enabled={settings.riskAlerts.enabled}
                onChange={(value) => updateNestedSettings('riskAlerts', 'enabled', value)}
              />
            </SettingRow>

            {settings.riskAlerts.enabled && (
              <>
                <SettingRow
                  icon={<AlertTriangle className="w-4 h-4" />}
                  label="Drawdown Threshold"
                  description="Alert when drawdown exceeds this percentage"
                >
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      min="5"
                      max="50"
                      value={settings.riskAlerts.drawdownThreshold}
                      onChange={(e) =>
                        updateNestedSettings('riskAlerts', 'drawdownThreshold', parseInt(e.target.value))
                      }
                      className="w-20 px-3 py-1.5 bg-slate-700 border border-slate-600 rounded-lg text-white text-sm text-right"
                    />
                    <span className="text-slate-400">%</span>
                  </div>
                </SettingRow>

                <SettingRow
                  icon={<AlertTriangle className="w-4 h-4" />}
                  label="Daily Loss Threshold"
                  description="Alert when daily loss exceeds this percentage"
                >
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      min="1"
                      max="20"
                      value={settings.riskAlerts.dailyLossThreshold}
                      onChange={(e) =>
                        updateNestedSettings('riskAlerts', 'dailyLossThreshold', parseInt(e.target.value))
                      }
                      className="w-20 px-3 py-1.5 bg-slate-700 border border-slate-600 rounded-lg text-white text-sm text-right"
                    />
                    <span className="text-slate-400">%</span>
                  </div>
                </SettingRow>
              </>
            )}
          </div>
        )}

        {/* Withdrawal Settings */}
        {activeSection === 'withdrawal' && (
          <div className="space-y-1">
            <SettingRow
              icon={<DollarSign className="w-4 h-4" />}
              label="Preferred Withdrawal Method"
              description="Default method for withdrawals"
            >
              <select
                value={settings.withdrawalSettings.preferredMethod}
                onChange={(e) =>
                  updateNestedSettings('withdrawalSettings', 'preferredMethod', e.target.value as 'bank' | 'crypto' | 'wallet')
                }
                className="px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="bank">Bank Transfer</option>
                <option value="crypto">Cryptocurrency</option>
                <option value="wallet">Platform Wallet</option>
              </select>
            </SettingRow>

            <SettingRow
              icon={<RefreshCw className="w-4 h-4" />}
              label="Auto-Withdraw"
              description="Automatically withdraw when balance exceeds threshold"
            >
              <ToggleSwitch
                enabled={settings.withdrawalSettings.autoWithdraw}
                onChange={(value) => updateNestedSettings('withdrawalSettings', 'autoWithdraw', value)}
              />
            </SettingRow>

            {settings.withdrawalSettings.autoWithdraw && (
              <SettingRow
                icon={<DollarSign className="w-4 h-4" />}
                label="Auto-Withdraw Threshold"
                description="Withdraw when balance exceeds this amount"
              >
                <div className="flex items-center gap-1">
                  <span className="text-slate-400">$</span>
                  <input
                    type="number"
                    min="1000"
                    step="100"
                    value={settings.withdrawalSettings.autoWithdrawThreshold}
                    onChange={(e) =>
                      updateNestedSettings('withdrawalSettings', 'autoWithdrawThreshold', parseInt(e.target.value))
                    }
                    className="w-28 px-3 py-1.5 bg-slate-700 border border-slate-600 rounded-lg text-white text-sm text-right"
                  />
                </div>
              </SettingRow>
            )}
          </div>
        )}
      </div>

      {/* Footer Actions */}
      <div className="p-5 border-t border-slate-700 bg-slate-900/30">
        <div className="flex items-center justify-end gap-3">
          {onCancel && (
            <button
              onClick={onCancel}
              disabled={isLoading}
              className="px-4 py-2 text-slate-300 hover:text-white transition-colors flex items-center gap-2"
            >
              <X className="w-4 h-4" />
              Cancel
            </button>
          )}
          <button
            onClick={handleSave}
            disabled={isLoading || !hasChanges}
            className="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
          >
            {isLoading ? (
              <>
                <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                </svg>
                Saving...
              </>
            ) : (
              <>
                <Save className="w-4 h-4" />
                Save Changes
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AccountSettingsPanel;
