import { useContext, useEffect, useState, useMemo } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { format, isAfter, isBefore, addDays } from 'date-fns'
import { FileText, Megaphone, AlertTriangle, ArrowRight, Clock, Wallet, TrendingUp, TrendingDown, DollarSign, Landmark, CheckSquare, FolderKanban } from 'lucide-react'
import { AppContext } from '../App'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import { api, PRIORITY_CONFIG } from '../utils/api'
import StatCard from '../components/StatCard'
import StatusBadge from '../components/StatusBadge'
import BrandBadge from '../components/BrandBadge'
import DatePresetPicker from '../components/DatePresetPicker'
import { SkeletonDashboard } from '../components/SkeletonLoader'

function getBudgetBarColor(percentage) {
  if (percentage > 90) return 'bg-red-500'
  if (percentage > 70) return 'bg-amber-500'
  return 'bg-emerald-500'
}

function FinanceMini({ finance }) {
  const { t, currencySymbol } = useLanguage()
  if (!finance) return null
  const totalReceived = finance.totalReceived || 0
  const spent = finance.spent || 0
  const remaining = finance.remaining || 0
  const roi = finance.roi || 0
  const totalExpenses = finance.totalExpenses || 0
  const campaignBudget = finance.totalCampaignBudget || 0
  const projectBudget = finance.totalProjectBudget || 0
  const unallocated = finance.unallocated ?? (totalReceived - campaignBudget - projectBudget)
  const pct = totalReceived > 0 ? (spent / totalReceived) * 100 : 0
  const barColor = getBudgetBarColor(pct)
  const campPct = totalReceived > 0 ? (campaignBudget / totalReceived) * 100 : 0
  const projPct = totalReceived > 0 ? (projectBudget / totalReceived) * 100 : 0

  return (
    <div className="bg-white rounded-xl border border-border p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold text-text-primary">{t('dashboard.budgetOverview')}</h3>
        <Link to="/finance" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
          {t('dashboard.details')} <ArrowRight className="w-3.5 h-3.5" />
        </Link>
      </div>

      {totalReceived === 0 ? (
        <div className="text-center py-6 text-sm text-text-tertiary">
          {t('dashboard.noBudgetRecorded')}. <Link to="/budgets" className="text-brand-primary underline">{t('dashboard.addBudget')}</Link>
        </div>
      ) : (
        <>
          {/* Spending bar */}
          <div className="mb-3">
            <div className="flex justify-between text-xs text-text-tertiary mb-1">
              <span>{spent.toLocaleString()} {currencySymbol} {t('dashboard.spent')}</span>
              <span>{totalReceived.toLocaleString()} {currencySymbol} {t('dashboard.received')}</span>
            </div>
            <div className="h-2.5 bg-surface-tertiary rounded-full overflow-hidden">
              <div className={`h-full ${barColor} rounded-full transition-all`} style={{ width: `${Math.min(pct, 100)}%` }} />
            </div>
          </div>

          {/* Allocation bar */}
          {(campaignBudget > 0 || projectBudget > 0) && (
            <div className="mb-3">
              <div className="text-[10px] text-text-tertiary mb-1 font-medium uppercase tracking-wide">Allocation</div>
              <div className="h-2 bg-surface-tertiary rounded-full overflow-hidden flex">
                {campPct > 0 && <div className="h-full bg-blue-500" style={{ width: `${campPct}%` }} />}
                {projPct > 0 && <div className="h-full bg-purple-500" style={{ width: `${projPct}%` }} />}
              </div>
              <div className="flex gap-3 mt-1 text-[10px] text-text-tertiary">
                {campaignBudget > 0 && <span><span className="inline-block w-1.5 h-1.5 rounded-full bg-blue-500 mr-1" />{campaignBudget.toLocaleString()}</span>}
                {projectBudget > 0 && <span><span className="inline-block w-1.5 h-1.5 rounded-full bg-purple-500 mr-1" />{projectBudget.toLocaleString()}</span>}
                {unallocated > 0 && <span><span className="inline-block w-1.5 h-1.5 rounded-full bg-gray-300 mr-1" />{unallocated.toLocaleString()} free</span>}
              </div>
            </div>
          )}

          {/* Key numbers */}
          <div className={`grid ${totalExpenses > 0 ? 'grid-cols-3' : 'grid-cols-2'} gap-3`}>
            <div className="text-center p-2 bg-surface-secondary rounded-lg">
              <Landmark className="w-4 h-4 mx-auto mb-1 text-emerald-500" />
              <div className={`text-sm font-bold ${remaining >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                {remaining.toLocaleString()}
              </div>
              <div className="text-[10px] text-text-tertiary">{t('dashboard.remaining')}</div>
            </div>
            {totalExpenses > 0 && (
              <div className="text-center p-2 bg-surface-secondary rounded-lg">
                <TrendingDown className="w-4 h-4 mx-auto mb-1 text-red-500" />
                <div className="text-sm font-bold text-red-600">
                  {totalExpenses.toLocaleString()}
                </div>
                <div className="text-[10px] text-text-tertiary">{t('dashboard.expenses')}</div>
              </div>
            )}
            <div className="text-center p-2 bg-surface-secondary rounded-lg">
              <TrendingUp className="w-4 h-4 mx-auto mb-1 text-blue-500" />
              <div className={`text-sm font-bold ${roi >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                {roi.toFixed(0)}%
              </div>
              <div className="text-[10px] text-text-tertiary">{t('dashboard.roi')}</div>
            </div>
          </div>
        </>
      )}
    </div>
  )
}

function ActiveCampaignsList({ campaigns, finance }) {
  const { t, currencySymbol } = useLanguage()
  const active = campaigns.filter(c => c.status === 'active')
  const campaignData = (finance?.campaigns || []).filter(c => c.status === 'active')

  if (active.length === 0) return null

  return (
    <div className="section-card">
      <div className="section-card-header flex items-center justify-between">
        <h3 className="font-semibold text-text-primary">{t('dashboard.activeCampaigns')}</h3>
        <Link to="/campaigns" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
          {t('dashboard.viewAll')} <ArrowRight className="w-3.5 h-3.5" />
        </Link>
      </div>
      <div className="divide-y divide-border-light">
        {active.slice(0, 5).map(c => {
          const cd = campaignData.find(d => d.id === (c._id || c.id)) || {}
          const spent = cd.tracks_spent || 0
          const allocated = cd.tracks_allocated || 0
          const pct = allocated > 0 ? (spent / allocated) * 100 : 0
          const barColor = getBudgetBarColor(pct)
          return (
            <Link key={c._id || c.id} to={`/campaigns/${c._id || c.id}`} className="flex items-center gap-4 px-5 py-3 hover:bg-surface-secondary transition-colors">
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-text-primary truncate">{c.name}</p>
                {allocated > 0 && (
                  <div className="mt-1.5 w-32">
                    <div className="flex justify-between text-[9px] text-text-tertiary mb-0.5">
                      <span>{spent.toLocaleString()}</span>
                      <span>{allocated.toLocaleString()} {currencySymbol}</span>
                    </div>
                    <div className="h-1.5 bg-surface-tertiary rounded-full overflow-hidden">
                      <div className={`h-full ${barColor} rounded-full`} style={{ width: `${Math.min(pct, 100)}%` }} />
                    </div>
                  </div>
                )}
              </div>
              <div className="text-right shrink-0">
                {cd.tracks_impressions > 0 && (
                  <div className="text-[10px] text-text-tertiary">
                    {cd.tracks_impressions.toLocaleString()} imp. / {cd.tracks_clicks.toLocaleString()} clicks
                  </div>
                )}
              </div>
            </Link>
          )
        })}
      </div>
    </div>
  )
}

function MyTasksList({ tasks, currentUserId, navigate, t }) {
  const myTasks = tasks
    .filter(task => {
      const assignedId = task.assigned_to_id || task.assignedTo
      return assignedId === currentUserId && task.status !== 'done'
    })
    .slice(0, 5)

  return (
    <div className="section-card">
      <div className="section-card-header flex items-center justify-between">
        <h3 className="font-semibold text-text-primary flex items-center gap-2">
          <CheckSquare className="w-4 h-4 text-brand-primary" />
          {t('dashboard.myTasks')}
        </h3>
        <Link to="/tasks" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
          {t('dashboard.viewAll')} <ArrowRight className="w-3.5 h-3.5" />
        </Link>
      </div>
      <div className="divide-y divide-border-light">
        {myTasks.length === 0 ? (
          <div className="py-8 text-center text-sm text-text-tertiary">
            {t('dashboard.allOnTrack')}
          </div>
        ) : (
          myTasks.map(task => (
            <div
              key={task._id || task.id}
              onClick={() => navigate('/tasks')}
              className="flex items-center gap-3 px-5 py-3 hover:bg-surface-secondary transition-colors cursor-pointer"
            >
              <div className={`w-2 h-2 rounded-full shrink-0 ${(PRIORITY_CONFIG[task.priority] || PRIORITY_CONFIG.medium).color}`} />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-text-primary truncate">{task.title}</p>
                <StatusBadge status={task.status} size="xs" />
              </div>
              {task.dueDate && (
                <div className="flex items-center gap-1 text-xs text-text-tertiary shrink-0">
                  <Clock className="w-3.5 h-3.5" />
                  {format(new Date(task.dueDate), 'MMM d')}
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  )
}

function ProjectProgress({ projects, tasks, t }) {
  if (!projects || projects.length === 0) return null

  const activeProjects = projects
    .filter(p => p.status === 'active' || p.status === 'in_progress')
    .slice(0, 5)

  if (activeProjects.length === 0) return null

  return (
    <div className="section-card">
      <div className="section-card-header flex items-center justify-between">
        <h3 className="font-semibold text-text-primary flex items-center gap-2">
          <FolderKanban className="w-4 h-4 text-purple-500" />
          {t('dashboard.projectProgress')}
        </h3>
        <Link to="/projects" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
          {t('dashboard.viewAll')} <ArrowRight className="w-3.5 h-3.5" />
        </Link>
      </div>
      <div className="divide-y divide-border-light">
        {activeProjects.map(project => {
          const projectId = project._id || project.id
          const projectTasks = tasks.filter(t => (t.project_id || t.projectId) === projectId)
          const doneTasks = projectTasks.filter(t => t.status === 'done').length
          const totalTasks = projectTasks.length
          const pct = totalTasks > 0 ? (doneTasks / totalTasks) * 100 : 0

          return (
            <Link key={projectId} to={`/projects/${projectId}`} className="flex items-center gap-4 px-5 py-3 hover:bg-surface-secondary transition-colors">
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-text-primary truncate">{project.name}</p>
                <div className="flex items-center gap-2 mt-1.5">
                  <div className="flex-1 h-1.5 bg-surface-tertiary rounded-full overflow-hidden max-w-[120px]">
                    <div className="h-full bg-purple-500 rounded-full transition-all" style={{ width: `${pct}%` }} />
                  </div>
                  <span className="text-[10px] text-text-tertiary shrink-0">
                    {doneTasks}/{totalTasks} {t('tasks.tasks')}
                  </span>
                </div>
              </div>
              <StatusBadge status={project.status} size="xs" />
            </Link>
          )
        })}
      </div>
    </div>
  )
}

export default function Dashboard() {
  const { t, currencySymbol } = useLanguage()
  const navigate = useNavigate()
  const { currentUser, teamMembers } = useContext(AppContext)
  const { hasModule } = useAuth()
  const [posts, setPosts] = useState([])
  const [campaigns, setCampaigns] = useState([])
  const [tasks, setTasks] = useState([])
  const [projects, setProjects] = useState([])
  const [finance, setFinance] = useState(null)
  const [loading, setLoading] = useState(true)

  // Date filtering
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [activePreset, setActivePreset] = useState('')

  useEffect(() => {
    loadData()
  }, [])

  const loadData = async () => {
    try {
      const fetches = []
      // Only fetch data for modules the user has access to
      if (hasModule('marketing')) {
        fetches.push(api.get('/posts?limit=50&sort=-createdAt').then(r => ({ key: 'posts', data: Array.isArray(r) ? r : [] })))
        fetches.push(api.get('/campaigns').then(r => ({ key: 'campaigns', data: Array.isArray(r) ? r : [] })))
      }
      if (hasModule('projects')) {
        fetches.push(api.get('/tasks').then(r => ({ key: 'tasks', data: Array.isArray(r) ? r : [] })))
        fetches.push(api.get('/projects').then(r => ({ key: 'projects', data: Array.isArray(r) ? r : [] })))
      }
      if (hasModule('finance')) {
        fetches.push(api.get('/finance/summary').then(r => ({ key: 'finance', data: r || null })))
      }

      const results = await Promise.allSettled(fetches)
      results.forEach(r => {
        if (r.status !== 'fulfilled') return
        const { key, data } = r.value
        if (key === 'posts') setPosts(data)
        else if (key === 'campaigns') setCampaigns(data)
        else if (key === 'tasks') setTasks(data)
        else if (key === 'projects') setProjects(data)
        else if (key === 'finance') setFinance(data)
      })
    } catch (err) {
      console.error('Dashboard load error:', err)
    } finally {
      setLoading(false)
    }
  }

  // Filtered data based on date range
  const filteredPosts = useMemo(() => {
    if (!dateFrom && !dateTo) return posts
    return posts.filter(p => {
      const d = p.scheduled_date || p.scheduledDate
      if (!d) return true
      if (dateFrom && d < dateFrom) return false
      if (dateTo && d > dateTo) return false
      return true
    })
  }, [posts, dateFrom, dateTo])

  const filteredTasks = useMemo(() => {
    if (!dateFrom && !dateTo) return tasks
    return tasks.filter(t => {
      const d = t.due_date || t.dueDate
      if (!d) return true
      if (dateFrom && d < dateFrom) return false
      if (dateTo && d > dateTo) return false
      return true
    })
  }, [tasks, dateFrom, dateTo])

  const activeCampaigns = campaigns.filter(c => c.status === 'active').length
  const overdueTasks = filteredTasks.filter(t =>
    t.dueDate && new Date(t.dueDate) < new Date() && t.status !== 'done'
  ).length

  const upcomingDeadlines = filteredTasks
    .filter(t => {
      if (!t.dueDate || t.status === 'done') return false
      const due = new Date(t.dueDate)
      const now = new Date()
      return isAfter(due, now) && isBefore(due, addDays(now, 7))
    })
    .sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate))
    .slice(0, 8)

  const statCards = []
  if (hasModule('marketing')) {
    statCards.push({
      icon: FileText,
      label: t('dashboard.totalPosts'),
      value: filteredPosts.length || 0,
      subtitle: `${filteredPosts.filter(p => p.status === 'published').length} ${t('dashboard.published')}`,
      color: 'brand-primary',
    })
    statCards.push({
      icon: Megaphone,
      label: t('dashboard.activeCampaigns'),
      value: activeCampaigns,
      subtitle: `${campaigns.length} ${t('dashboard.total')}`,
      color: 'brand-secondary',
    })
  }
  if (hasModule('finance')) {
    statCards.push({
      icon: Landmark,
      label: t('dashboard.budgetRemaining'),
      value: `${(finance?.remaining ?? 0).toLocaleString()}`,
      subtitle: finance?.totalReceived ? `${(finance.spent || 0).toLocaleString()} ${t('dashboard.spent')} ${t('dashboard.of')} ${finance.totalReceived.toLocaleString()} ${currencySymbol}` : t('dashboard.noBudget'),
      color: 'brand-tertiary',
    })
  }
  if (hasModule('projects')) {
    statCards.push({
      icon: AlertTriangle,
      label: t('dashboard.overdueTasks'),
      value: overdueTasks,
      subtitle: overdueTasks > 0 ? t('dashboard.needsAttention') : t('dashboard.allOnTrack'),
      color: 'brand-quaternary',
    })
  }

  if (loading) {
    return <SkeletonDashboard />
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Welcome + Date presets */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gradient">
            {t('dashboard.welcomeBack')}, {currentUser?.name || 'there'}
          </h1>
          <p className="text-text-secondary mt-1">
            {t('dashboard.happeningToday')}
          </p>
        </div>
        <DatePresetPicker
          activePreset={activePreset}
          onSelect={(from, to, key) => { setDateFrom(from); setDateTo(to); setActivePreset(key) }}
          onClear={() => { setDateFrom(''); setDateTo(''); setActivePreset('') }}
        />
      </div>

      {/* Stats */}
      {statCards.length > 0 && (
        <div className={`grid grid-cols-1 sm:grid-cols-2 ${statCards.length >= 4 ? 'lg:grid-cols-4' : statCards.length === 3 ? 'lg:grid-cols-3' : 'lg:grid-cols-2'} gap-4 stagger-children`}>
          {statCards.map((card, i) => (
            <StatCard key={i} {...card} />
          ))}
        </div>
      )}

      {/* My Tasks + Project Progress */}
      {hasModule('projects') && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <MyTasksList tasks={filteredTasks} currentUserId={currentUser?.id || currentUser?._id} navigate={navigate} t={t} />
          <ProjectProgress projects={projects} tasks={tasks} t={t} />
        </div>
      )}

      {/* Budget + Active Campaigns */}
      {(hasModule('finance') || hasModule('marketing')) && (
        <div className={`grid grid-cols-1 ${hasModule('finance') && hasModule('marketing') ? 'lg:grid-cols-3' : ''} gap-6`}>
          {hasModule('finance') && <FinanceMini finance={finance} />}
          {hasModule('marketing') && (
            <div className={hasModule('finance') ? 'lg:col-span-2' : ''}>
              <ActiveCampaignsList campaigns={campaigns} finance={finance} />
            </div>
          )}
        </div>
      )}

      {/* Recent Posts + Upcoming Deadlines */}
      {(hasModule('marketing') || hasModule('projects')) && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Recent Posts */}
          {hasModule('marketing') && (
            <div className="section-card">
              <div className="section-card-header flex items-center justify-between">
                <h3 className="font-semibold text-text-primary">{t('dashboard.recentPosts')}</h3>
                <Link to="/posts" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
                  {t('dashboard.viewAll')} <ArrowRight className="w-3.5 h-3.5" />
                </Link>
              </div>
              <div className="divide-y divide-border-light">
                {filteredPosts.length === 0 ? (
                  <div className="py-12 text-center text-sm text-text-tertiary">
                    {t('dashboard.noPostsYet')}
                  </div>
                ) : (
                  filteredPosts.slice(0, 8).map((post) => (
                    <div
                      key={post._id}
                      onClick={() => navigate('/posts')}
                      className="flex items-center gap-3 px-5 py-3 hover:bg-surface-secondary transition-colors cursor-pointer"
                    >
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-text-primary truncate">{post.title}</p>
                        <div className="flex items-center gap-2 mt-1">
                          {post.brand && <BrandBadge brand={post.brand} />}
                        </div>
                      </div>
                      <StatusBadge status={post.status} size="xs" />
                    </div>
                  ))
                )}
              </div>
            </div>
          )}

          {/* Upcoming Deadlines */}
          {hasModule('projects') && (
            <div className="section-card">
              <div className="section-card-header flex items-center justify-between">
                <h3 className="font-semibold text-text-primary">{t('dashboard.upcomingDeadlines')}</h3>
                <Link to="/tasks" className="text-sm text-brand-primary hover:text-brand-primary-light font-medium flex items-center gap-1">
                  {t('dashboard.viewAll')} <ArrowRight className="w-3.5 h-3.5" />
                </Link>
              </div>
              <div className="divide-y divide-border-light">
                {upcomingDeadlines.length === 0 ? (
                  <div className="py-12 text-center text-sm text-text-tertiary">
                    {t('dashboard.noUpcomingDeadlines')}
                  </div>
                ) : (
                  upcomingDeadlines.map((task) => (
                    <div
                      key={task._id}
                      onClick={() => navigate('/tasks')}
                      className="flex items-center gap-3 px-5 py-3 hover:bg-surface-secondary transition-colors cursor-pointer"
                    >
                      <div className={`w-2 h-2 rounded-full ${(PRIORITY_CONFIG[task.priority] || PRIORITY_CONFIG.medium).color}`} />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-text-primary truncate">{task.title}</p>
                        <div className="flex items-center gap-2 mt-0.5">
                          <StatusBadge status={task.status} size="xs" />
                          {task.assignedName && (
                            <span className="text-xs text-text-tertiary truncate">{task.assignedName}</span>
                          )}
                        </div>
                      </div>
                      <div className="flex items-center gap-1 text-xs text-text-tertiary shrink-0">
                        <Clock className="w-3.5 h-3.5" />
                        {format(new Date(task.dueDate), 'MMM d')}
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
