import { useState, useEffect } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { api } from '@/lib/api'
import { 
  Mail, 
  Inbox, 
  Tag, 
  Clock, 
  TrendingUp, 
  Plus, 
  Settings, 
  LogOut,
  Zap,
  BarChart3,
  Users,
  FileText,
  Bell,
  Shield,
  HelpCircle,
  ChevronRight,
  Loader2,
  RefreshCw,
  Check,
  AlertCircle,
  Sparkles,
  AlertTriangle,
  Lightbulb,
  Archive
} from 'lucide-react'

interface EmailStats {
  totalSorted: number
  todaySorted: number
  weekSorted: number
  categories: Record<string, number>
  timeSaved: number
}

interface EmailAccount {
  id: string
  email: string
  provider: string
  connected: boolean
  lastSync?: string
}

interface SortResult {
  sorted: number
  inboxCleared: number
  categories: Record<string, number>
  timeSaved: { minutes: number; formatted: string }
  highlights: Array<{ type: string; count: number; message: string }>
  suggestions: Array<{ type: string; message: string }>
  provider?: string
  isDemo?: boolean
}

interface Digest {
  date: string
  totalSorted: number
  inboxCleared: number
  timeSavedMinutes: number
  stats: Record<string, number>
  highlights: Array<{ type: string; count: number; message: string }>
  suggestions: Array<{ type: string; message: string }>
  hasData: boolean
}

export function Dashboard() {
  const { user, logout } = useAuth()
  const navigate = useNavigate()
  const [stats, setStats] = useState<EmailStats | null>(null)
  const [accounts, setAccounts] = useState<EmailAccount[]>([])
  const [digest, setDigest] = useState<Digest | null>(null)
  const [loading, setLoading] = useState(true)
  const [sorting, setSorting] = useState(false)
  const [sortResult, setSortResult] = useState<SortResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (user?.$id) {
      loadData()
    }
  }, [user])

  const loadData = async () => {
    if (!user?.$id) return
    setLoading(true)
    setError(null)
    
    try {
      const [statsRes, accountsRes, digestRes] = await Promise.all([
        api.getEmailStats(user.$id),
        api.getEmailAccounts(user.$id),
        api.getDigest(user.$id),
      ])
      
      if (statsRes.data) setStats(statsRes.data)
      if (accountsRes.data) setAccounts(accountsRes.data)
      if (digestRes.data) setDigest(digestRes.data)
    } catch (err) {
      console.error('Error loading dashboard data:', err)
      setError('Failed to load data')
    } finally {
      setLoading(false)
    }
  }

  const handleSortNow = async () => {
    if (!user?.$id || accounts.length === 0) {
      setError('Connect an email account first to start sorting.')
      return
    }
    
    setSorting(true)
    setSortResult(null)
    setError(null)
    
    try {
      const result = await api.sortEmails(user.$id, accounts[0].id)
      if (result.data) {
        setSortResult(result.data)
        // Refresh stats and digest
        const [statsRes, digestRes] = await Promise.all([
          api.getEmailStats(user.$id),
          api.getDigest(user.$id),
        ])
        if (statsRes.data) setStats(statsRes.data)
        if (digestRes.data) setDigest(digestRes.data)
      } else if (result.error) {
        setError(result.error.message || 'Sorting failed')
      }
    } catch (err) {
      console.error('Error sorting emails:', err)
      setError('Error sorting emails')
    } finally {
      setSorting(false)
    }
  }

  const handleConnectDemo = async () => {
    if (!user?.$id) return
    
    setLoading(true)
    setError(null)
    
    try {
      const result = await api.connectDemoAccount(user.$id)
      if (result.data) {
        const accountsRes = await api.getEmailAccounts(user.$id)
        if (accountsRes.data) setAccounts(accountsRes.data)
      } else if (result.error) {
        setError(result.error.message || 'Could not create demo account')
      }
    } catch (err) {
      console.error('Error connecting demo:', err)
      setError('Error creating demo account')
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    await logout()
    navigate('/')
  }

  const displayStats: EmailStats = stats || {
    totalSorted: 0,
    todaySorted: 0,
    weekSorted: 0,
    categories: {},
    timeSaved: 0,
  }

  const categoryColors: Record<string, string> = {
    'vip': 'bg-amber-500',
    'Important': 'bg-amber-500',
    'customers': 'bg-blue-500',
    'Clients': 'bg-blue-500',
    'invoices': 'bg-green-500',
    'Invoices': 'bg-green-500',
    'newsletters': 'bg-purple-500',
    'Newsletter': 'bg-purple-500',
    'social': 'bg-pink-500',
    'Social': 'bg-pink-500',
    'promotions': 'bg-orange-500',
    'Promotions': 'bg-orange-500',
    'security': 'bg-red-500',
    'Security': 'bg-red-500',
    'calendar': 'bg-indigo-500',
    'Calendar': 'bg-indigo-500',
    'review': 'bg-slate-500',
    'Review': 'bg-slate-500',
  }

  const categoryLabels: Record<string, string> = {
    'vip': 'Important',
    'customers': 'Clients',
    'invoices': 'Invoices',
    'newsletters': 'Newsletter',
    'social': 'Social',
    'promotions': 'Promotions',
    'security': 'Security',
    'calendar': 'Calendar',
    'review': 'Review',
  }

  const formatCategoryName = (key: string) => categoryLabels[key] || key

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100">
      {/* Header */}
      <header className="bg-white/90 backdrop-blur-md border-b border-slate-200 sticky top-0 z-50 shadow-sm">
        <div className="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-14 sm:h-16">
            <Link to="/" className="flex items-center gap-1.5 sm:gap-2 flex-shrink-0">
              <div className="w-8 h-8 sm:w-9 sm:h-9 rounded-lg bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center shadow-lg shadow-primary-500/20">
                <Mail className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
              </div>
              <span className="text-base sm:text-lg font-bold text-slate-900 whitespace-nowrap">
                Email<span className="text-primary-600">Sorter</span>
              </span>
            </Link>

            <div className="flex items-center gap-1.5 sm:gap-2 lg:gap-4">
              <Button variant="ghost" size="icon" className="hidden lg:flex h-9 w-9">
                <Bell className="w-5 h-5 text-slate-500" />
              </Button>
              <Button variant="ghost" size="icon" className="hidden lg:flex h-9 w-9">
                <HelpCircle className="w-5 h-5 text-slate-500" />
              </Button>
              <div className="hidden lg:block h-6 w-px bg-slate-200" />
              <Button 
                variant="ghost" 
                onClick={() => navigate('/settings')} 
                className="hidden lg:flex h-9"
              >
                <Settings className="w-4 h-4 mr-2" />
                Settings
              </Button>
              <Button 
                variant="ghost" 
                size="icon" 
                className="lg:hidden h-9 w-9" 
                onClick={() => navigate('/settings')}
                title="Settings"
              >
                <Settings className="w-5 h-5 text-slate-600" />
              </Button>
              <Button 
                variant="outline" 
                onClick={handleLogout} 
                className="hidden lg:flex h-9"
              >
                <LogOut className="w-4 h-4 mr-2" />
                Sign out
              </Button>
              <Button 
                variant="outline" 
                size="icon" 
                className="lg:hidden h-9 w-9" 
                onClick={handleLogout}
                title="Sign out"
              >
                <LogOut className="w-4 h-4 text-slate-600" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 sm:py-6">
        {/* Welcome section */}
        <div className="mb-4 sm:mb-6">
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900 mb-0.5">
            Welcome back{user?.name ? `, ${user.name}` : ''}! 👋
          </h1>
          <p className="text-xs sm:text-sm text-slate-600">
            Your email overview for today.
          </p>
        </div>

        {/* Error message */}
        {error && (
          <div className="mb-3 sm:mb-4 p-2.5 sm:p-3 bg-red-50 border border-red-200 rounded-lg flex items-start sm:items-center gap-2 text-red-700">
            <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5 sm:mt-0" />
            <p className="text-xs sm:text-sm flex-1">{error}</p>
            <button onClick={() => setError(null)} className="text-red-400 hover:text-red-600 text-base font-semibold leading-none">
              ✕
            </button>
          </div>
        )}

        {/* Sort Result Toast */}
        {sortResult && (
          <div className="mb-3 sm:mb-4 p-2.5 sm:p-3 bg-green-50 border border-green-200 rounded-lg">
            <div className="flex items-center justify-between mb-2 flex-wrap gap-1.5">
              <div className="flex items-center gap-2 text-green-700">
                <Check className="w-4 h-4 flex-shrink-0" />
                <p className="text-xs sm:text-sm font-semibold">Sorting complete!</p>
              </div>
              {sortResult.isDemo && (
                <Badge variant="secondary" className="bg-amber-100 text-amber-700 text-xs">
                  Demo
                </Badge>
              )}
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3 text-xs">
              <div>
                <p className="text-xs text-green-600 mb-0.5">Sorted</p>
                <p className="text-lg sm:text-xl font-bold text-green-800">{sortResult.sorted}</p>
              </div>
              <div>
                <p className="text-xs text-green-600 mb-0.5">Time saved</p>
                <p className="text-lg sm:text-xl font-bold text-green-800">{sortResult.timeSaved.formatted}</p>
              </div>
              {Object.entries(sortResult.categories).slice(0, 2).map(([cat, count]) => (
                <div key={cat}>
                  <p className="text-xs text-green-600 mb-0.5 truncate">{formatCategoryName(cat)}</p>
                  <p className="text-lg sm:text-xl font-bold text-green-800">{count}</p>
                </div>
              ))}
            </div>
            {Object.keys(sortResult.categories).length > 2 && (
              <div className="mt-2 pt-2 border-t border-green-200">
                <p className="text-xs text-green-600 mb-1.5">Categories:</p>
                <div className="flex flex-wrap gap-1">
                  {Object.entries(sortResult.categories).map(([cat, count]) => (
                    <span 
                      key={cat} 
                      className={`px-1.5 py-0.5 rounded-full text-xs font-medium text-white ${categoryColors[cat] || 'bg-slate-500'}`}
                    >
                      {formatCategoryName(cat)}: {count}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="text-center">
              <Loader2 className="w-10 h-10 animate-spin text-primary-500 mx-auto mb-4" />
              <p className="text-slate-500">Loading dashboard...</p>
            </div>
          </div>
        ) : (
          <>
            {/* Daily Digest Card */}
            {digest?.hasData && (
              <Card className="mb-4 sm:mb-6 shadow-lg border-0 bg-gradient-to-r from-primary-50 via-white to-accent-50 overflow-hidden">
                <CardContent className="p-3 sm:p-4">
                  <div className="flex items-start justify-between mb-3 gap-2">
                    <div className="flex items-center gap-2 flex-1 min-w-0">
                      <div className="w-9 h-9 sm:w-10 sm:h-10 rounded-lg bg-gradient-to-br from-primary-500 to-accent-500 flex items-center justify-center shadow-lg shadow-primary-500/30 flex-shrink-0">
                        <Sparkles className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <h3 className="text-sm sm:text-base font-bold text-slate-900 truncate">Today's Digest</h3>
                        <p className="text-xs text-slate-500 truncate">{new Date(digest.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</p>
                      </div>
                    </div>
                    {digest.inboxCleared > 0 && (
                      <Badge className="bg-green-100 text-green-700 border-green-200 text-xs whitespace-nowrap flex-shrink-0">
                        <Archive className="w-3 h-3 mr-0.5" />
                        {digest.inboxCleared}
                      </Badge>
                    )}
                  </div>

                  <div className="grid grid-cols-3 gap-2 mb-3">
                    <div className="bg-white/80 rounded-lg p-2 sm:p-3 border border-slate-200/50">
                      <p className="text-xs text-slate-500 mb-0.5">Processed</p>
                      <p className="text-base sm:text-lg font-bold text-slate-900">{digest.totalSorted}</p>
                    </div>
                    <div className="bg-white/80 rounded-lg p-2 sm:p-3 border border-slate-200/50">
                      <p className="text-xs text-slate-500 mb-0.5">Cleared</p>
                      <p className="text-base sm:text-lg font-bold text-green-600">{digest.inboxCleared}</p>
                    </div>
                    <div className="bg-white/80 rounded-lg p-2 sm:p-3 border border-slate-200/50">
                      <p className="text-xs text-slate-500 mb-0.5">Saved</p>
                      <p className="text-base sm:text-lg font-bold text-primary-600">
                        {digest.timeSavedMinutes > 60 
                          ? `${Math.floor(digest.timeSavedMinutes / 60)}h ${digest.timeSavedMinutes % 60}m`
                          : `${digest.timeSavedMinutes}m`}
                      </p>
                    </div>
                  </div>

                  {/* Highlights */}
                  {digest.highlights.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-medium text-slate-700 mb-1.5 flex items-center gap-1.5">
                        <AlertTriangle className="w-3.5 h-3.5 text-amber-500" />
                        Needs Attention
                      </p>
                      <div className="flex flex-wrap gap-1.5">
                        {digest.highlights.map((highlight, idx) => (
                          <div 
                            key={idx}
                            className={`px-2 py-1 rounded-md text-xs ${
                              highlight.type === 'vip' ? 'bg-amber-100 text-amber-800' :
                              highlight.type === 'security' ? 'bg-red-100 text-red-800' :
                              highlight.type === 'invoices' ? 'bg-green-100 text-green-800' :
                              'bg-slate-100 text-slate-700'
                            }`}
                          >
                            {highlight.message}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Suggestions */}
                  {digest.suggestions.length > 0 && (
                    <div className="pt-2.5 border-t border-slate-200/50">
                      <p className="text-xs font-medium text-slate-700 mb-1.5 flex items-center gap-1.5">
                        <Lightbulb className="w-3.5 h-3.5 text-primary-500" />
                        Suggestions
                      </p>
                      <div className="space-y-1">
                        {digest.suggestions.map((suggestion, idx) => (
                          <p key={idx} className="text-xs text-slate-600 bg-white/60 rounded-md px-2 py-1">
                            {suggestion.message}
                          </p>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Stats cards */}
            <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3 lg:gap-4 mb-4 sm:mb-6">
              <StatsCard
                icon={Inbox}
                title="Sorted today"
                value={displayStats.todaySorted.toString()}
                subtitle="emails"
                color="bg-primary-500"
              />
              <StatsCard
                icon={TrendingUp}
                title="This week"
                value={displayStats.weekSorted.toString()}
                subtitle="emails"
                color="bg-accent-500"
              />
              <StatsCard
                icon={Clock}
                title="Time saved"
                value={displayStats.timeSaved > 60 
                  ? `${Math.floor(displayStats.timeSaved / 60)}h ${displayStats.timeSaved % 60}m`
                  : `${displayStats.timeSaved}m`}
                subtitle="this week"
                color="bg-green-500"
              />
              <StatsCard
                icon={BarChart3}
                title="Total sorted"
                value={displayStats.totalSorted.toLocaleString('en-US')}
                subtitle="emails"
                color="bg-violet-500"
              />
            </div>

            <div className="grid lg:grid-cols-3 gap-3 sm:gap-4">
              {/* Categories breakdown */}
              <Card className="lg:col-span-2 shadow-lg border-0 order-2 lg:order-1">
                <CardHeader className="p-3 sm:p-4 pb-2 sm:pb-3">
                  <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
                    <Tag className="w-4 h-4 text-primary-500" />
                    Categories Overview
                  </CardTitle>
                  <CardDescription className="text-xs">
                    Distribution this week
                  </CardDescription>
                </CardHeader>
                <CardContent className="p-3 sm:p-4 pt-0">
                  {Object.keys(displayStats.categories).length > 0 ? (
                    <div className="space-y-2.5">
                      {Object.entries(displayStats.categories).map(([category, count]) => {
                        const total = Object.values(displayStats.categories).reduce((a, b) => a + b, 0)
                        const percentage = total > 0 ? Math.round((count / total) * 100) : 0
                        
                        return (
                          <div key={category}>
                            <div className="flex items-center justify-between mb-1">
                              <div className="flex items-center gap-1.5 min-w-0 flex-1">
                                <div className={`w-2 h-2 sm:w-2.5 sm:h-2.5 rounded-full flex-shrink-0 ${categoryColors[category] || 'bg-slate-400'}`} />
                                <span className="text-xs font-medium text-slate-700 truncate">{formatCategoryName(category)}</span>
                              </div>
                              <div className="flex items-center gap-1 flex-shrink-0">
                                <span className="text-xs text-slate-500 whitespace-nowrap">{count}</span>
                                <span className="text-xs text-slate-400 whitespace-nowrap">({percentage}%)</span>
                              </div>
                            </div>
                            <div className="h-1.5 bg-slate-100 rounded-full overflow-hidden">
                              <div 
                                className={`h-full rounded-full transition-all duration-500 ${categoryColors[category] || 'bg-slate-400'}`}
                                style={{ width: `${percentage}%` }}
                              />
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  ) : (
                    <div className="text-center py-8">
                      <Tag className="w-10 h-10 text-slate-300 mx-auto mb-3" />
                      <p className="text-xs text-slate-500 mb-1">No category statistics yet</p>
                      <p className="text-xs text-slate-400">Start a sort to see statistics</p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Connected accounts */}
              <Card className="shadow-lg border-0 order-1 lg:order-2">
                <CardHeader className="p-3 sm:p-4 pb-2 sm:pb-3">
                  <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
                    <Users className="w-4 h-4 text-primary-500" />
                    Email Accounts
                  </CardTitle>
                  <CardDescription className="text-xs">
                    Connected mailboxes
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-2.5 sm:space-y-3 p-3 sm:p-4 pt-0">
                  {accounts.length > 0 ? (
                    accounts.map((account) => (
                      <div 
                        key={account.id}
                        className="flex items-center justify-between p-2 sm:p-2.5 bg-gradient-to-r from-slate-50 to-slate-100 rounded-lg gap-2"
                      >
                        <div className="flex items-center gap-2 min-w-0 flex-1">
                          <div className={`w-8 h-8 sm:w-9 sm:h-9 rounded-lg flex items-center justify-center shadow-sm flex-shrink-0 ${
                            account.provider === 'gmail' ? 'bg-red-100' : 'bg-blue-100'
                          }`}>
                            <Mail className={`w-3.5 h-3.5 sm:w-4 sm:h-4 ${
                              account.provider === 'gmail' ? 'text-red-600' : 'text-blue-600'
                            }`} />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-xs font-medium text-slate-700 truncate">{account.email}</p>
                            <p className="text-xs text-slate-500 capitalize truncate">{account.provider}</p>
                          </div>
                        </div>
                        <Badge variant={account.connected ? 'success' : 'secondary'} className="text-xs whitespace-nowrap flex-shrink-0 px-1.5 py-0.5">
                          {account.connected ? 'Active' : 'Off'}
                        </Badge>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-6">
                      <div className="w-12 h-12 mx-auto mb-3 rounded-xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center">
                        <Mail className="w-6 h-6 text-slate-400" />
                      </div>
                      <p className="text-xs text-slate-500 mb-1">
                        No email accounts connected
                      </p>
                      <p className="text-xs text-slate-400">
                        Connect an account to get started
                      </p>
                    </div>
                  )}
                  
                  <div className="space-y-1.5 pt-2">
                    <Button 
                      className="w-full h-9 sm:h-10 text-xs sm:text-sm" 
                      variant="outline" 
                      onClick={() => navigate('/setup')}
                    >
                      <Plus className="w-3.5 h-3.5 mr-1.5" />
                      Connect account
                    </Button>
                    {accounts.length === 0 && (
                      <Button 
                        className="w-full h-9 sm:h-10 text-xs sm:text-sm" 
                        variant="ghost" 
                        onClick={handleConnectDemo}
                        disabled={loading}
                      >
                        <Zap className="w-3.5 h-3.5 mr-1.5" />
                        Try demo account
                      </Button>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Quick actions */}
            <div className="mt-4 sm:mt-6">
              <h2 className="text-sm sm:text-base font-semibold text-slate-900 mb-2.5 sm:mb-3">Quick Actions</h2>
              <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3">
                <QuickAction
                  icon={sorting ? RefreshCw : Zap}
                  title={sorting ? "Sorting..." : "Sort now"}
                  description={sorting ? "Please wait..." : "Start manual sorting"}
                  onClick={handleSortNow}
                  disabled={sorting || accounts.length === 0}
                  loading={sorting}
                  highlight
                />
                <QuickAction
                  icon={Settings}
                  title="Adjust rules"
                  description="Edit sorting rules"
                  onClick={() => navigate('/settings?tab=rules')}
                />
                <QuickAction
                  icon={Shield}
                  title="VIP List"
                  description="Manage important contacts"
                  onClick={() => navigate('/settings?tab=vip')}
                />
                <QuickAction
                  icon={FileText}
                  title="Reports"
                  description="Detailed statistics"
                  onClick={() => {}}
                  disabled
                />
              </div>
            </div>
          </>
        )}
      </main>
    </div>
  )
}

interface StatsCardProps {
  icon: React.ElementType
  title: string
  value: string
  subtitle: string
  color: string
}

function StatsCard({ icon: Icon, title, value, subtitle, color }: StatsCardProps) {
  return (
    <Card className="shadow-lg border-0 overflow-hidden">
      <CardContent className="p-3 sm:p-4">
        <div className="flex items-start justify-between">
          <div className="min-w-0 flex-1">
            <p className="text-xs text-slate-500 mb-0.5 truncate">{title}</p>
            <p className="text-xl sm:text-2xl font-bold text-slate-900 leading-tight">{value}</p>
            <p className="text-xs text-slate-400 truncate mt-0.5">{subtitle}</p>
          </div>
          <div className={`w-9 h-9 sm:w-10 sm:h-10 rounded-lg ${color} flex items-center justify-center shadow-lg flex-shrink-0`}>
            <Icon className="w-4 h-4 sm:w-5 sm:h-5 text-white" />
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

interface QuickActionProps {
  icon: React.ElementType
  title: string
  description: string
  onClick: () => void
  disabled?: boolean
  loading?: boolean
  highlight?: boolean
}

function QuickAction({ icon: Icon, title, description, onClick, disabled, loading, highlight }: QuickActionProps) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`flex items-center gap-2 p-2.5 sm:p-3 rounded-lg border-2 transition-all text-left w-full group disabled:opacity-50 disabled:cursor-not-allowed ${
        highlight && !disabled
          ? 'bg-gradient-to-r from-primary-50 to-accent-50 border-primary-200 hover:border-primary-400 hover:shadow-lg hover:shadow-primary-500/10 active:scale-[0.98]'
          : 'bg-white border-slate-200 hover:border-primary-200 hover:shadow-md active:scale-[0.98]'
      }`}
    >
      <div className={`w-9 h-9 sm:w-10 sm:h-10 rounded-lg flex items-center justify-center transition-colors flex-shrink-0 ${
        highlight && !disabled
          ? 'bg-primary-500 shadow-lg shadow-primary-500/30'
          : 'bg-primary-50 group-hover:bg-primary-100'
      }`}>
        <Icon className={`w-4 h-4 sm:w-5 sm:h-5 ${highlight && !disabled ? 'text-white' : 'text-primary-600'} ${loading ? 'animate-spin' : ''}`} />
      </div>
      <div className="flex-1 min-w-0">
        <p className={`text-xs sm:text-sm font-semibold ${highlight && !disabled ? 'text-primary-900' : 'text-slate-900'} truncate`}>{title}</p>
        <p className="text-xs text-slate-500 truncate leading-tight">{description}</p>
      </div>
      <ChevronRight className={`w-3.5 h-3.5 sm:w-4 sm:h-4 transition-colors flex-shrink-0 ${
        highlight && !disabled ? 'text-primary-400' : 'text-slate-400'
      } group-hover:text-primary-500 group-hover:translate-x-0.5 transition-transform`} />
    </button>
  )
}
