'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Building2, Users, UserPlus, Mail, Crown, Shield, Star, X, AlertCircle,
  CheckCircle2, Loader2, Pencil, CreditCard, MapPin, FileText, Landmark, Wallet
} from 'lucide-react';
import { useSession } from '../lib/session-context';
import CardSetupForm from './CardSetupModal';

interface CompanyData {
  id: string;
  name: string;
  package: string;
  maxUsers: number;
  ownerId: string;
  userCount: number;
  financialData?: {
    billingAddress?: string;
    taxId?: string;
    vatNumber?: string;
    billingEmail?: string;
  };
  createdAt: string;
}

interface CompanyPaymentMethod {
  type: string;
  last4?: string;
  brand?: string;
  expiryMonth?: number;
  expiryYear?: number;
  email?: string;
  accountHolderName?: string;
  bankCode?: string;
  country?: string;
  stripePaymentMethodId?: string;
}

interface BillingPaymentMethod {
  id: string;
  type: string;
  isDefault: boolean;
  last4?: string;
  brand?: string;
  expMonth?: number;
  expYear?: number;
  email?: string;
  bankCode?: string;
  country?: string;
}

interface CompanyUser {
  id: string;
  email: string;
  name: string | null;
  role: string;
  isOwner: boolean;
  emailVerified: boolean;
  createdAt: string;
}

interface AvailableUser {
  id: string;
  email: string;
  name: string | null;
  role: string;
  emailVerified: boolean;
  createdAt: string;
}

const TIER_CONFIG = {
  starter: { label: 'Starter', color: 'text-sky-400', bg: 'bg-sky-500/10', icon: Star },
  professional: { label: 'Professional', color: 'text-purple-400', bg: 'bg-purple-500/10', icon: Crown },
  enterprise: { label: 'Enterprise', color: 'text-amber-400', bg: 'bg-amber-500/10', icon: Shield },
};

export default function CompanyDashboard() {
  const { user: sessionUser } = useSession();
  const [activeTab, setActiveTab] = useState<'details' | 'users'>('details');
  const [company, setCompany] = useState<CompanyData | null>(null);
  const [users, setUsers] = useState<CompanyUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Modal state
  const [showAddUser, setShowAddUser] = useState(false);
  const [addUserMode, setAddUserMode] = useState<'create' | 'existing'>('create');
  const [newUser, setNewUser] = useState({ email: '', name: '', password: '', confirmPassword: '' });
  const [selectedExistingUserId, setSelectedExistingUserId] = useState('');
  const [availableUsers, setAvailableUsers] = useState<AvailableUser[]>([]);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  
  // Financial data edit state
  const [showEditFinancial, setShowEditFinancial] = useState(false);
  const [financialForm, setFinancialForm] = useState({
    billingAddress: '',
    billingEmail: '',
    taxId: '',
    vatNumber: '',
  });

  // Payment method state (owner only)
  const [companyPaymentMethod, setCompanyPaymentMethod] = useState<CompanyPaymentMethod | null>(null);
  const [paymentMethodsCount, setPaymentMethodsCount] = useState(0);
  const [paymentMethods, setPaymentMethods] = useState<BillingPaymentMethod[]>([]);
  const [pmLoading, setPmLoading] = useState(false);
  const [showEditPayment, setShowEditPayment] = useState(false);
  const [showStripeForm, setShowStripeForm] = useState(false);
  const [pmError, setPmError] = useState<string | null>(null);

  useEffect(() => {
    loadCompanyData();
    loadCompanyPaymentMethod();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const loadCompanyData = async () => {
    if (!sessionUser?.companyId) return;

    setLoading(true);
    try {
      const [companyRes, usersRes] = await Promise.all([
        fetch(`/api/companies/${sessionUser.companyId}`, { credentials: 'include' }),
        fetch(`/api/companies/${sessionUser.companyId}/users`, { credentials: 'include' }),
      ]);

      if (!companyRes.ok || !usersRes.ok) {
        throw new Error('Failed to load company data');
      }

      const companyData = await companyRes.json();
      const usersData = await usersRes.json();

      setCompany(companyData.company);
      setUsers(usersData.users || []);
      setAvailableUsers(usersData.availableUsers || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const loadCompanyPaymentMethod = async () => {
    if (!sessionUser?.companyId || !sessionUser.isOwner) return;
    setPmLoading(true);
    try {
      const [companyRes, listRes] = await Promise.all([
        fetch(`/api/companies/${sessionUser.companyId}/payment-method`, { credentials: 'include' }),
        fetch('/api/billing/payment-method', { credentials: 'include' }),
      ]);
      if (companyRes.ok) {
        const data = await companyRes.json();
        setCompanyPaymentMethod(data.paymentMethod ?? null);
      }
      if (listRes.ok) {
        const data = await listRes.json();
        const methods = Array.isArray(data.methods) ? data.methods : [];
        setPaymentMethods(methods);
        setPaymentMethodsCount(methods.length);
      }
    } catch {}
    finally { setPmLoading(false); }
  };

  const saveCompanyPaymentMethod = async (pm: CompanyPaymentMethod) => {
    if (!sessionUser?.companyId) return;
    await fetch(`/api/companies/${sessionUser.companyId}/payment-method`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(pm),
    });
    setCompanyPaymentMethod(pm);
  };

  const handleStripePaymentSuccess = async (pmId: string) => {
    // Determine type from Stripe by fetching the method list
    try {
      const res = await fetch('/api/billing/payment-method', { credentials: 'include' });
      const { methods } = await res.json();
      const pm = methods?.find((m: { id: string }) => m.id === pmId);
      if (pm) {
        await saveCompanyPaymentMethod({
          type: pm.type === 'sepa_debit' ? 'sepa_debit' : pm.type,
          last4: pm.last4,
          brand: pm.brand,
          expiryMonth: pm.expMonth,
          expiryYear: pm.expYear,
          email: pm.email,
          bankCode: pm.bankCode,
          country: pm.country,
          stripePaymentMethodId: pmId,
        });
      }
    } catch {}
    await loadCompanyPaymentMethod();
    setShowStripeForm(false);
    setShowEditPayment(false);
    setPmError(null);
  };

  const handleDeleteCompanyPaymentMethod = async (paymentMethodId: string) => {
    if (!sessionUser?.companyId) return;
    if (!confirm('Remove this payment method from company profile? This action cannot be undone.')) return;
    try {
      setPmError(null);
      const detachRes = await fetch('/api/billing/payment-method', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ paymentMethodId }),
      });
      if (!detachRes.ok) {
        const data = await detachRes.json().catch(() => null);
        throw new Error(data?.error || 'Failed to remove payment method');
      }
      await loadCompanyPaymentMethod();
    } catch (err) {
      setPmError(err instanceof Error ? err.message : 'Failed to remove payment method');
    }
  };

  const handleAddUser = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!sessionUser?.companyId) return;
    
    setSaving(true);
    setFormError(null);
    
    try {
      if (addUserMode === 'create' && newUser.password !== newUser.confirmPassword) {
        throw new Error('Password and confirm password do not match');
      }
      const payload =
        addUserMode === 'existing'
          ? { existingUserId: selectedExistingUserId }
          : { email: newUser.email, name: newUser.name, password: newUser.password };

      const res = await fetch(`/api/companies/${sessionUser.companyId}/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
        credentials: 'include',
      });
      
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to create user');
      }
      
      setShowAddUser(false);
      setAddUserMode('create');
      setSelectedExistingUserId('');
      setNewUser({ email: '', name: '', password: '', confirmPassword: '' });
      await loadCompanyData();
    } catch (err) {
      setFormError(err instanceof Error ? err.message : 'Failed to create user');
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteUser = async (userId: string) => {
    if (!confirm('Are you sure you want to remove this user from your company?')) return;
    
    try {
      const res = await fetch(`/api/companies/${sessionUser?.companyId}/users?userId=${userId}`, {
        method: 'DELETE',
        credentials: 'include',
      });
      
      if (!res.ok) throw new Error('Failed to delete user');
      await loadCompanyData();
    } catch {
      setError('Failed to delete user');
    }
  };

  // Helper to check if financial data has any actual values
  const hasFinancialData = (data?: CompanyData['financialData']) => {
    if (!data) return false;
    return !!(data.billingAddress || data.billingEmail || data.taxId || data.vatNumber);
  };

  // Load financial data into form when opening edit modal
  useEffect(() => {
    if (showEditFinancial && company?.financialData) {
      setFinancialForm({
        billingAddress: company.financialData.billingAddress || '',
        billingEmail: company.financialData.billingEmail || '',
        taxId: company.financialData.taxId || '',
        vatNumber: company.financialData.vatNumber || '',
      });
    }
  }, [showEditFinancial, company?.financialData]);

  const handleUpdateFinancial = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!sessionUser?.companyId) return;
    
    setSaving(true);
    setFormError(null);
    
    try {
      const res = await fetch(`/api/companies/${sessionUser.companyId}/financial`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          billingAddress: financialForm.billingAddress || undefined,
          billingEmail: financialForm.billingEmail || undefined,
          taxId: financialForm.taxId || undefined,
          vatNumber: financialForm.vatNumber || undefined,
        }),
        credentials: 'include',
      });
      
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to update financial data');
      }
      
      setShowEditFinancial(false);
      await loadCompanyData();
    } catch (err) {
      setFormError(err instanceof Error ? err.message : 'Failed to update financial data');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-accent" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
          <p className="text-red-400">{error}</p>
        </div>
      </div>
    );
  }

  if (!company) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <Building2 className="w-12 h-12 text-muted mx-auto mb-3" />
          <p className="text-muted">No company found</p>
        </div>
      </div>
    );
  }

  const tierConfig = TIER_CONFIG[company.package as keyof typeof TIER_CONFIG] || TIER_CONFIG.starter;
  const TierIcon = tierConfig.icon;
  const isUnlimitedUsers = company.maxUsers >= 9999;
  const remainingSlots = isUnlimitedUsers ? Infinity : company.maxUsers - company.userCount;

  return (
    <div className="space-y-6">
      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Building2 className="w-6 h-6 text-accent-light" /> Company
          </h2>
          <p className="text-sm text-muted mt-1">Manage your company and team members</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setActiveTab('details')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all cursor-pointer ${
              activeTab === 'details' ? 'bg-accent/20 text-accent-light' : 'text-muted hover:text-foreground'
            }`}
          >
            Details
          </button>
          <button
            onClick={() => setActiveTab('users')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all cursor-pointer ${
              activeTab === 'users' ? 'bg-accent/20 text-accent-light' : 'text-muted hover:text-foreground'
            }`}
          >
            <Users className="w-4 h-4 inline mr-1" /> Team
          </button>
        </div>
      </motion.div>

      {/* Content */}
      {activeTab === 'details' ? (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-6">
          {/* Company Card */}
          <div className="glass rounded-xl p-6">
            <div className="flex items-start gap-4">
              <div className="w-16 h-16 rounded-xl gradient-accent flex items-center justify-center text-white">
                <Building2 className="w-8 h-8" />
              </div>
              <div className="flex-1">
                <h3 className="text-xl font-bold text-foreground">{company.name}</h3>
                <div className="flex items-center gap-3 mt-2">
                  <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold ${tierConfig.color} ${tierConfig.bg}`}>
                    <TierIcon className="w-3.5 h-3.5" />
                    {tierConfig.label}
                  </span>
                  <span className="text-sm text-muted">
                    {company.userCount} / {isUnlimitedUsers ? '∞' : company.maxUsers} users
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Stats Grid */}
          <div className="grid grid-cols-3 gap-4">
            <div className="glass rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Users className="w-4 h-4 text-accent-light" />
                <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Team Members</p>
              </div>
              <p className="text-2xl font-bold text-foreground">{company.userCount}</p>
            </div>
            <div className="glass rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <UserPlus className="w-4 h-4 text-purple-400" />
                <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Available Slots</p>
              </div>
              <p className="text-2xl font-bold text-foreground">{isUnlimitedUsers ? '∞' : remainingSlots}</p>
            </div>
            <div className="glass rounded-xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Crown className="w-4 h-4 text-amber-400" />
                <p className="text-[10px] text-muted uppercase tracking-wider font-medium">Package</p>
              </div>
              <p className="text-2xl font-bold text-foreground">{tierConfig.label}</p>
            </div>
          </div>

          {/* Financial Data - Owner Only */}
          {sessionUser?.isOwner && (
            <div className="glass rounded-xl p-6">
              <div className="flex items-center justify-between mb-4">
                <h4 className="text-sm font-semibold text-foreground">Financial Information</h4>
                <button
                  onClick={() => setShowEditFinancial(true)}
                  className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-surface-light text-xs text-muted hover:text-foreground transition cursor-pointer"
                >
                  <Pencil className="w-3 h-3" /> Edit
                </button>
              </div>
              {hasFinancialData(company.financialData) ? (
                <div className="grid grid-cols-2 gap-4 text-sm">
                  {company.financialData?.billingAddress && (
                    <div>
                      <p className="text-muted text-xs mb-1">Billing Address</p>
                      <p className="text-foreground">{company.financialData.billingAddress}</p>
                    </div>
                  )}
                  {company.financialData?.billingEmail && (
                    <div>
                      <p className="text-muted text-xs mb-1">Billing Email</p>
                      <p className="text-foreground">{company.financialData.billingEmail}</p>
                    </div>
                  )}
                  {company.financialData?.taxId && (
                    <div>
                      <p className="text-muted text-xs mb-1">Tax ID</p>
                      <p className="text-foreground">{company.financialData.taxId}</p>
                    </div>
                  )}
                  {company.financialData?.vatNumber && (
                    <div>
                      <p className="text-muted text-xs mb-1">VAT Number</p>
                      <p className="text-foreground">{company.financialData.vatNumber}</p>
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-sm text-muted">No financial information set. Click Edit to add.</p>
              )}
            </div>
          )}

          {/* Payment Method - Owner Only */}
          {sessionUser?.isOwner && (
            <div className="glass rounded-xl p-6">
              <div className="flex items-center justify-between mb-4">
                <h4 className="text-sm font-semibold text-foreground flex items-center gap-2">
                  <CreditCard className="w-4 h-4 text-muted" />
                  Payment Method
                  {paymentMethodsCount > 0 && paymentMethodsCount <= 1 && (
                    <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20">
                      Keep at least 2 methods
                    </span>
                  )}
                </h4>
                <div className="flex items-center gap-2">
                  {paymentMethodsCount > 0 && (
                    <button
                      onClick={() => { setShowEditPayment(true); setPmError(null); setShowStripeForm(true); }}
                      className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-surface-light text-xs text-accent-light hover:text-accent transition cursor-pointer"
                      title="Add another payment method"
                    >
                      <CreditCard className="w-3 h-3" /> Add Another
                    </button>
                  )}
                  <button
                    onClick={() => { setShowEditPayment(true); setPmError(null); setShowStripeForm(false); }}
                    className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-surface-light text-xs text-muted hover:text-foreground transition cursor-pointer"
                  >
                    <Pencil className="w-3 h-3" /> {companyPaymentMethod ? 'Edit' : 'Add'}
                  </button>
                </div>
              </div>

              {pmLoading ? (
                <div className="flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin text-muted" />
                  <span className="text-xs text-muted">Loading…</span>
                </div>
              ) : paymentMethodsCount > 0 ? (
                <div className="space-y-2">
                  {paymentMethods.map((pm) => (
                    <div key={pm.id} className="flex items-center gap-3 p-3 rounded-lg bg-surface/40 border border-border/60">
                      {pm.type === 'paypal' ? (
                        <Wallet className="w-5 h-5 text-blue-400 shrink-0" />
                      ) : pm.type === 'sepa_debit' || pm.type === 'sepa' ? (
                        <Landmark className="w-5 h-5 text-green-400 shrink-0" />
                      ) : (
                        <CreditCard className="w-5 h-5 text-accent-light shrink-0" />
                      )}
                      <div className="min-w-0 flex-1">
                        {(pm.type === 'card' || pm.type === 'link' || pm.type === 'apple_pay' || pm.type === 'google_pay') && (
                          <>
                            <p className="text-sm font-medium text-foreground capitalize">
                              {pm.brand || 'Card'} ···· {pm.last4 ?? '—'}
                              {pm.isDefault && (
                                <span className="ml-2 px-1.5 py-0.5 rounded text-[10px] bg-accent/20 text-accent-light">Default</span>
                              )}
                            </p>
                            {pm.expMonth && (
                              <p className="text-xs text-muted">Expires {pm.expMonth}/{pm.expYear}</p>
                            )}
                          </>
                        )}
                        {pm.type === 'paypal' && (
                          <>
                            <p className="text-sm font-medium text-foreground">
                              PayPal
                              {pm.isDefault && (
                                <span className="ml-2 px-1.5 py-0.5 rounded text-[10px] bg-accent/20 text-accent-light">Default</span>
                              )}
                            </p>
                            {pm.email && <p className="text-xs text-muted">{pm.email}</p>}
                          </>
                        )}
                        {(pm.type === 'sepa_debit' || pm.type === 'sepa') && (
                          <>
                            <p className="text-sm font-medium text-foreground">
                              Bank Account ···· {pm.last4 ?? '—'}
                              {pm.isDefault && (
                                <span className="ml-2 px-1.5 py-0.5 rounded text-[10px] bg-accent/20 text-accent-light">Default</span>
                              )}
                            </p>
                            <p className="text-xs text-muted">{pm.country ?? ''} SEPA</p>
                          </>
                        )}
                      </div>
                      <button
                        onClick={() => handleDeleteCompanyPaymentMethod(pm.id)}
                        disabled={paymentMethodsCount <= 1}
                        title={paymentMethodsCount <= 1 ? 'Add a second payment method before removing this one' : 'Remove payment method'}
                        className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-surface-light text-xs transition ${
                          paymentMethodsCount <= 1
                            ? 'text-danger/40 cursor-not-allowed'
                            : 'text-danger/70 hover:text-danger cursor-pointer'
                        }`}
                      >
                        <X className="w-3 h-3" /> Remove
                      </button>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted">No payment method on file.</p>
              )}
              {paymentMethodsCount > 0 && paymentMethodsCount <= 1 && (
                <p className="text-[11px] text-amber-400 mt-3">
                  You cannot remove your only payment method. Add a second method first.
                </p>
              )}
            </div>
          )}
        </motion.div>
      ) : (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-4">
          {/* Users Header */}
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-foreground">Team Members</h3>
              <p className="text-sm text-muted">
                {company.userCount} of {isUnlimitedUsers ? '∞' : company.maxUsers} users • {isUnlimitedUsers ? 'Unlimited slots' : `${remainingSlots} slots remaining`}
              </p>
            </div>
            {sessionUser?.isOwner && remainingSlots > 0 && (
              <button
                onClick={() => {
                  setShowAddUser(true);
                  setFormError(null);
                  setAddUserMode('create');
                  setSelectedExistingUserId('');
                  setNewUser({ email: '', name: '', password: '', confirmPassword: '' });
                }}
                className="flex items-center gap-2 px-4 py-2 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer"
              >
                <UserPlus className="w-4 h-4" /> Add Member
              </button>
            )}
          </div>

          {/* Users List */}
          <div className="glass rounded-xl overflow-hidden">
            <div className="grid grid-cols-[1fr_100px_100px_80px] gap-3 px-4 py-2.5 bg-surface text-[10px] text-muted uppercase tracking-wider font-semibold border-b border-border">
              <span>User</span>
              <span>Role</span>
              <span>Status</span>
              <span className="text-right">Actions</span>
            </div>
            
            {users.length === 0 ? (
              <div className="py-12 text-center text-sm text-muted">
                No team members yet. <button onClick={() => {
                  setShowAddUser(true);
                  setFormError(null);
                  setAddUserMode('create');
                  setSelectedExistingUserId('');
                  setNewUser({ email: '', name: '', password: '', confirmPassword: '' });
                }} className="text-accent-light hover:underline cursor-pointer">Add one?</button>
              </div>
            ) : (
              <div>
                {users.map((user, i) => (
                  <div key={user.id}
                    className={`grid grid-cols-[1fr_100px_100px_80px] gap-3 px-4 py-3 items-center text-xs border-t border-border/50 ${
                      i % 2 !== 0 ? 'bg-surface/30' : ''
                    }`}>
                    <div className="min-w-0">
                      <p className="font-medium text-foreground truncate">{user.name || '—'}</p>
                      <p className="text-[10px] text-muted truncate">{user.email}</p>
                    </div>
                    <span>
                      {user.isOwner ? (
                        <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-amber-500/10 text-amber-400">
                          Owner
                        </span>
                      ) : (
                        <span className="px-2 py-0.5 rounded-full text-[10px] font-semibold bg-surface-light text-muted">
                          Member
                        </span>
                      )}
                    </span>
                    <span>
                      {user.emailVerified ? (
                        <span className="flex items-center gap-1 text-[10px] text-green-400">
                          <CheckCircle2 className="w-3 h-3" /> Verified
                        </span>
                      ) : (
                        <span className="text-[10px] text-amber-400">Pending</span>
                      )}
                    </span>
                    <div className="flex items-center justify-end">
                      {!user.isOwner && (
                        <button 
                          onClick={() => handleDeleteUser(user.id)}
                          className="p-1.5 rounded hover:bg-red-500/10 cursor-pointer text-muted hover:text-red-400 transition-colors"
                          title="Remove user"
                        >
                          <X className="w-3.5 h-3.5" />
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </motion.div>
      )}

      {/* Add User Modal */}
      <AnimatePresence>
        {showAddUser && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
            <motion.div initial={{ opacity: 0, scale: 0.95, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-md glass rounded-2xl p-6 border border-border">
              <div className="flex items-center justify-between mb-5">
                <h3 className="text-base font-bold text-foreground">Add Team Member</h3>
                <button onClick={() => setShowAddUser(false)} className="p-1.5 rounded hover:bg-surface-light cursor-pointer">
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              {formError && (
                <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400">
                  {formError}
                </div>
              )}

              <form onSubmit={handleAddUser} className="space-y-4">
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">Add Method</label>
                  <div className="grid grid-cols-2 gap-2">
                    <button
                      type="button"
                      onClick={() => setAddUserMode('create')}
                      className={`rounded-lg px-3 py-2 text-xs font-medium transition ${
                        addUserMode === 'create'
                          ? 'bg-accent/20 text-accent-light border border-accent/40'
                          : 'bg-surface border border-border text-muted hover:text-foreground'
                      }`}
                    >
                      Create New User
                    </button>
                    <button
                      type="button"
                      onClick={() => setAddUserMode('existing')}
                      className={`rounded-lg px-3 py-2 text-xs font-medium transition ${
                        addUserMode === 'existing'
                          ? 'bg-accent/20 text-accent-light border border-accent/40'
                          : 'bg-surface border border-border text-muted hover:text-foreground'
                      }`}
                    >
                      Use Existing User
                    </button>
                  </div>
                </div>

                {addUserMode === 'existing' && (
                  <div>
                    <label className="block text-xs font-medium text-muted mb-1.5">
                      Existing User <span className="text-red-400">*</span>
                    </label>
                    <select
                      required
                      value={selectedExistingUserId}
                      onChange={e => setSelectedExistingUserId(e.target.value)}
                      className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition cursor-pointer"
                    >
                      <option value="">Select a user...</option>
                      {availableUsers.filter(user => user.role !== 'admin').map(user => (
                        <option key={user.id} value={user.id}>
                          {user.name ? `${user.name} (${user.email})` : user.email}
                        </option>
                      ))}
                    </select>
                    {availableUsers.length === 0 && (
                      <p className="text-[10px] text-muted mt-1">No unassigned users available. Create a new one instead.</p>
                    )}
                  </div>
                )}

                {addUserMode === 'create' && (
                  <>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Email <span className="text-red-400">*</span>
                  </label>
                  <input 
                    type="email" 
                    required 
                    value={newUser.email} 
                    onChange={e => setNewUser({ ...newUser, email: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Name
                  </label>
                  <input 
                    type="text" 
                    value={newUser.name} 
                    onChange={e => setNewUser({ ...newUser, name: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Password <span className="text-red-400">*</span>
                  </label>
                  <input 
                    type="password" 
                    required 
                    value={newUser.password} 
                    onChange={e => setNewUser({ ...newUser, password: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-muted mb-1.5">
                    Confirm Password <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="password"
                    required
                    value={newUser.confirmPassword}
                    onChange={e => setNewUser({ ...newUser, confirmPassword: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition"
                  />
                </div>
                  </>
                )}
                
                <div className="flex gap-3 pt-2">
                  <button 
                    type="button" 
                    onClick={() => {
                      setShowAddUser(false);
                      setAddUserMode('create');
                      setSelectedExistingUserId('');
                      setNewUser({ email: '', name: '', password: '', confirmPassword: '' });
                    }}
                    className="flex-1 py-2.5 rounded-lg glass-light text-sm text-muted hover:text-foreground transition cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit" 
                    disabled={saving}
                    className="flex-1 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer disabled:opacity-50"
                  >
                    {saving ? 'Adding…' : addUserMode === 'existing' ? 'Add Existing User' : 'Add Member'}
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Edit Payment Method Modal */}
      <AnimatePresence>
        {showEditPayment && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
            <motion.div initial={{ opacity: 0, scale: 0.95, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-4xl glass rounded-2xl p-6 border border-border">
              <div className="flex items-center justify-between mb-5">
                <h3 className="text-base font-bold text-foreground flex items-center gap-2">
                  <CreditCard className="w-4 h-4" /> Payment Method
                </h3>
                <button onClick={() => { setShowEditPayment(false); setShowStripeForm(false); }} className="p-1.5 rounded hover:bg-surface-light cursor-pointer">
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              {pmError && (
                <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400">{pmError}</div>
              )}

              {!showStripeForm && (
                <div className="space-y-4">
                  <p className="text-xs text-muted">
                    Add a payment method via Stripe. Available options (card, PayPal, SEPA, wallets) depend on your Stripe account settings.
                  </p>
                  <button
                    onClick={() => setShowStripeForm(true)}
                    className="w-full py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer flex items-center justify-center gap-2"
                  >
                    <CreditCard className="w-4 h-4" /> Set up payment method
                  </button>
                </div>
              )}

              {showStripeForm && (
                <CardSetupForm
                  onSuccess={handleStripePaymentSuccess}
                  onCancel={() => setShowStripeForm(false)}
                />
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Edit Financial Data Modal */}
      <AnimatePresence>
        {showEditFinancial && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
            <motion.div initial={{ opacity: 0, scale: 0.95, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-md glass rounded-2xl p-6 border border-border">
              <div className="flex items-center justify-between mb-5">
                <h3 className="text-base font-bold text-foreground flex items-center gap-2">
                  <FileText className="w-4 h-4" /> Edit Financial Information
                </h3>
                <button onClick={() => setShowEditFinancial(false)} className="p-1.5 rounded hover:bg-surface-light cursor-pointer">
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              {formError && (
                <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400">
                  {formError}
                </div>
              )}

              <form onSubmit={handleUpdateFinancial} className="space-y-4">
                <div>
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted mb-1.5">
                    <MapPin className="w-3 h-3" /> Billing Address
                  </label>
                  <textarea 
                    value={financialForm.billingAddress} 
                    onChange={e => setFinancialForm({ ...financialForm, billingAddress: e.target.value })}
                    rows={2}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition resize-none" 
                  />
                </div>
                <div>
                  <label className="flex items-center gap-1.5 text-xs font-medium text-muted mb-1.5">
                    <Mail className="w-3 h-3" /> Billing Email
                  </label>
                  <input 
                    type="email" 
                    value={financialForm.billingEmail} 
                    onChange={e => setFinancialForm({ ...financialForm, billingEmail: e.target.value })}
                    className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                  />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-muted mb-1.5">
                      Tax ID
                    </label>
                    <input 
                      type="text" 
                      value={financialForm.taxId} 
                      onChange={e => setFinancialForm({ ...financialForm, taxId: e.target.value })}
                      className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-muted mb-1.5">
                      VAT Number
                    </label>
                    <input 
                      type="text" 
                      value={financialForm.vatNumber} 
                      onChange={e => setFinancialForm({ ...financialForm, vatNumber: e.target.value })}
                      className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-accent/60 transition" 
                    />
                  </div>
                </div>
                
                <div className="flex gap-3 pt-2">
                  <button 
                    type="button" 
                    onClick={() => setShowEditFinancial(false)}
                    className="flex-1 py-2.5 rounded-lg glass-light text-sm text-muted hover:text-foreground transition cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit" 
                    disabled={saving}
                    className="flex-1 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer disabled:opacity-50"
                  >
                    {saving ? 'Saving…' : 'Save Changes'}
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
