import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  Cell,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import {
  Activity,
  ArrowRight,
  ArrowUpRight,
  BookOpen,
  CalendarRange,
  Clock,
  FileText,
  FolderKanban,
  Mail,
  MapPin,
  Megaphone,
  MessageSquare,
  Monitor,
  Plus,
  Settings,
  ShieldCheck,
  Users,
} from 'lucide-react'
import { fetchUsers } from '@/lib/api/users'
import { fetchCategories } from '@/lib/api/categories'
import { fetchCourses } from '@/lib/api/courses'
import { fetchSchedules } from '@/lib/api/schedules'
import { fetchAnnouncements } from '@/lib/api/announcements'
import { fetchLeads } from '@/lib/api/leads'
import { fetchComments } from '@/lib/api/comments'
import { fetchPages } from '@/lib/api/pages'
import { fetchFaqs } from '@/lib/api/faqs'
import { fetchHeroSlides } from '@/lib/api/hero-slides'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { DashboardHeader } from './components/dashboard-header'
import {
  CmsRow,
  EmptyPlaceholder,
  LoadingPlaceholder,
  MiniStat,
  StatusDot,
  timeAgo,
} from './components/dashboard-helpers'

const CHART_COLORS = ['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ec4899', '#06b6d4']
const DASH_STALE = 5 * 60 * 1000 // 5 dk cache

export function Dashboard2() {
  const usersQ = useQuery({ queryKey: ['dash2', 'users'], queryFn: () => fetchUsers({ page: 1, perPage: 1 }), staleTime: DASH_STALE })
  const categoriesQ = useQuery({ queryKey: ['dash2', 'categories'], queryFn: () => fetchCategories({ page: 1, perPage: 100 }), staleTime: DASH_STALE })
  const coursesQ = useQuery({ queryKey: ['dash2', 'courses'], queryFn: () => fetchCourses({ page: 1, perPage: 100 }), staleTime: DASH_STALE })
  const schedulesQ = useQuery({ queryKey: ['dash2', 'schedules'], queryFn: () => fetchSchedules({ page: 1, perPage: 10 }), staleTime: DASH_STALE })
  const announcementsQ = useQuery({ queryKey: ['dash2', 'announcements'], queryFn: () => fetchAnnouncements({ page: 1, perPage: 5 }), staleTime: DASH_STALE })
  const leadsQ = useQuery({ queryKey: ['dash2', 'leads'], queryFn: () => fetchLeads({ page: 1, perPage: 8 }), staleTime: DASH_STALE })
  const commentsQ = useQuery({ queryKey: ['dash2', 'comments'], queryFn: () => fetchComments({ page: 1, perPage: 5 }), staleTime: DASH_STALE })
  const pagesQ = useQuery({ queryKey: ['dash2', 'pages'], queryFn: () => fetchPages({ page: 1, perPage: 1 }), staleTime: DASH_STALE })
  const faqsQ = useQuery({ queryKey: ['dash2', 'faqs'], queryFn: () => fetchFaqs({ page: 1, perPage: 1 }), staleTime: DASH_STALE })
  const heroSlidesQ = useQuery({ queryKey: ['dash2', 'hero-slides'], queryFn: () => fetchHeroSlides({ page: 1, perPage: 1 }), staleTime: DASH_STALE })

  const totalLeads = leadsQ.data?.meta.total ?? 0
  const unreadLeads = leadsQ.data?.items.filter((l) => !l.isRead).length ?? 0
  const totalComments = commentsQ.data?.meta.total ?? 0

  const categoryDistribution = useMemo(() => {
    const courses = coursesQ.data?.items ?? []
    const map = new Map<string, number>()
    for (const c of courses) { const name = c.categoryName || 'Diğer'; map.set(name, (map.get(name) ?? 0) + 1) }
    return Array.from(map.entries()).map(([name, value]) => ({ name, value })).sort((a, b) => b.value - a.value).slice(0, 6)
  }, [coursesQ.data])

  const leadSourceData = useMemo(() => {
    const leads = leadsQ.data?.items ?? []
    const map = new Map<string, number>()
    for (const l of leads) { const source = l.source ?? 'Bilinmiyor'; map.set(source, (map.get(source) ?? 0) + 1) }
    const labels: Record<string, string> = { hero_form: 'Hero Form', contact_form: 'İletişim', consultation_form: 'Danışmanlık', whatsapp_widget: 'WhatsApp', Bilinmiyor: 'Diğer' }
    return Array.from(map.entries()).map(([source, count]) => ({ name: labels[source] ?? source, count }))
  }, [leadsQ.data])

  const scheduleCapacity = useMemo(() => {
    return (schedulesQ.data?.items ?? []).slice(0, 8).map((s) => ({
      name: s.courseTitle.length > 12 ? s.courseTitle.slice(0, 12) + '\u2026' : s.courseTitle,
      doluluk: s.quota > 0 ? Math.round(((s.quota - s.availableSeats) / s.quota) * 100) : 0,
      kontenjan: s.quota,
    }))
  }, [schedulesQ.data])

  const recentActivity = useMemo(() => {
    const items: Array<{ id: string; type: string; icon: React.ElementType; text: string; time: string | null; color: string }> = []
    for (const lead of (leadsQ.data?.items ?? []).slice(0, 3)) {
      items.push({ id: `lead-${lead.id}`, type: 'lead', icon: Mail, text: `${lead.name} yeni başvuru yaptı`, time: lead.createdAt, color: 'text-amber-600 bg-amber-100 dark:bg-amber-900/40' })
    }
    for (const ann of (announcementsQ.data?.items ?? []).slice(0, 2)) {
      items.push({ id: `ann-${ann.id}`, type: 'announcement', icon: Megaphone, text: `"${ann.title}" duyurusu yayınlandı`, time: ann.publishedAt ?? ann.createdAt, color: 'text-blue-600 bg-blue-100 dark:bg-blue-900/40' })
    }
    for (const comment of (commentsQ.data?.items ?? []).slice(0, 2)) {
      items.push({ id: `comment-${comment.id}`, type: 'comment', icon: MessageSquare, text: `${comment.authorName} yeni yorum bıraktı`, time: comment.createdAt, color: 'text-violet-600 bg-violet-100 dark:bg-violet-900/40' })
    }
    return items.sort((a, b) => { if (!a.time) return 1; if (!b.time) return -1; return new Date(b.time).getTime() - new Date(a.time).getTime() }).slice(0, 6)
  }, [leadsQ.data, announcementsQ.data, commentsQ.data])

  const now = new Date()
  const hours = now.getHours()
  const greeting = hours < 12 ? 'G\u00FCnayd\u0131n' : hours < 18 ? '\u0130yi g\u00FCnler' : '\u0130yi ak\u015Famlar'

  return (
    <>
      <DashboardHeader />
      <Main className='space-y-6'>
        <div className='flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between'>
          <div>
            <h1 className='text-2xl font-bold tracking-tight md:text-3xl'>{greeting} \uD83D\uDC4B</h1>
            <p className='text-sm text-muted-foreground'>{now.toLocaleDateString('tr-TR', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
          </div>
          <div className='flex gap-2'>
            <Button asChild size='sm' className='rounded-xl'><Link to='/courses/create'><Plus className='size-4' />Eğitim</Link></Button>
            <Button asChild variant='outline' size='sm' className='rounded-xl'><Link to='/announcements/create'><Plus className='size-4' />Duyuru</Link></Button>
            <Button asChild variant='outline' size='sm' className='rounded-xl'><Link to='/pages/create'><Plus className='size-4' />Sayfa</Link></Button>
          </div>
        </div>

        <section className='grid gap-3 grid-cols-2 sm:grid-cols-3 lg:grid-cols-6'>
          <MiniStat icon={FolderKanban} label='Kategori' value={categoriesQ.data?.meta.total ?? 0} href='/categories' color='text-blue-600' bg='bg-blue-500/10' />
          <MiniStat icon={BookOpen} label='Eğitim' value={coursesQ.data?.meta.total ?? 0} href='/courses' color='text-emerald-600' bg='bg-emerald-500/10' />
          <MiniStat icon={CalendarRange} label='Takvim' value={schedulesQ.data?.meta.total ?? 0} href='/schedules' color='text-violet-600' bg='bg-violet-500/10' />
          <MiniStat icon={Megaphone} label='Duyuru' value={announcementsQ.data?.meta.total ?? 0} href='/announcements' color='text-orange-600' bg='bg-orange-500/10' />
          <MiniStat icon={FileText} label='Sayfa' value={pagesQ.data?.meta.total ?? 0} href='/pages' color='text-pink-600' bg='bg-pink-500/10' />
          <MiniStat icon={Users} label='Yönetici' value={usersQ.data?.meta.total ?? 0} href='/users' color='text-amber-600' bg='bg-amber-500/10' />
        </section>

        {(unreadLeads > 0 || totalComments > 0) && (
          <section className='grid gap-4 sm:grid-cols-2'>
            {unreadLeads > 0 && (
              <Link to='/leads'>
                <div className='flex items-center gap-4 rounded-2xl border border-amber-200 bg-amber-50/80 px-5 py-4 transition hover:shadow-md dark:border-amber-900/50 dark:bg-amber-950/20'>
                  <div className='flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/40'><Mail className='size-5 text-amber-700 dark:text-amber-400' /></div>
                  <div className='flex-1'><p className='text-sm font-semibold text-amber-900 dark:text-amber-200'>{unreadLeads} okunmamış başvuru</p><p className='text-xs text-amber-700/70'>Toplam {totalLeads} başvuru</p></div>
                  <ArrowRight className='size-4 text-amber-600' />
                </div>
              </Link>
            )}
            {totalComments > 0 && (
              <Link to='/comments'>
                <div className='flex items-center gap-4 rounded-2xl border border-blue-200 bg-blue-50/80 px-5 py-4 transition hover:shadow-md dark:border-blue-900/50 dark:bg-blue-950/20'>
                  <div className='flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/40'><MessageSquare className='size-5 text-blue-700 dark:text-blue-400' /></div>
                  <div className='flex-1'><p className='text-sm font-semibold text-blue-900 dark:text-blue-200'>{totalComments} yorum bekliyor</p><p className='text-xs text-blue-700/70'>Onay ve yanıt bekliyor</p></div>
                  <ArrowRight className='size-4 text-blue-600' />
                </div>
              </Link>
            )}
          </section>
        )}

        <section className='grid gap-6 lg:grid-cols-2'>
          <Card className='border-border/70'>
            <CardHeader className='pb-2'><CardTitle className='text-base'>Eğitim Dağılımı</CardTitle><CardDescription>Kategorilere göre eğitim sayıları</CardDescription></CardHeader>
            <CardContent>
              {categoryDistribution.length === 0 ? (<EmptyPlaceholder text='Veri yok' />) : (
                <div className='flex items-center gap-6'>
                  <ResponsiveContainer width={180} height={180}>
                    <PieChart><Pie data={categoryDistribution} dataKey='value' nameKey='name' cx='50%' cy='50%' innerRadius={50} outerRadius={80} paddingAngle={3} strokeWidth={0}>{categoryDistribution.map((_, i) => (<Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />))}</Pie><Tooltip contentStyle={{ borderRadius: 12, fontSize: 12 }} formatter={(value: number) => [`${value} eğitim`, '']} /></PieChart>
                  </ResponsiveContainer>
                  <div className='flex-1 space-y-2'>{categoryDistribution.map((item, i) => (<div key={item.name} className='flex items-center gap-2 text-sm'><span className='h-3 w-3 shrink-0 rounded-full' style={{ backgroundColor: CHART_COLORS[i % CHART_COLORS.length] }} /><span className='flex-1 truncate text-muted-foreground'>{item.name}</span><span className='font-semibold tabular-nums'>{item.value}</span></div>))}</div>
                </div>
              )}
            </CardContent>
          </Card>
          <Card className='border-border/70'>
            <CardHeader className='pb-2'><CardTitle className='text-base'>Başvuru Kaynakları</CardTitle><CardDescription>Formlardan gelen başvuru dağılımı</CardDescription></CardHeader>
            <CardContent>
              {leadSourceData.length === 0 ? (<EmptyPlaceholder text='Veri yok' />) : (
                <ResponsiveContainer width='100%' height={180}>
                  <BarChart data={leadSourceData} layout='vertical' margin={{ left: 0 }}><XAxis type='number' hide /><YAxis type='category' dataKey='name' width={90} tick={{ fontSize: 12 }} tickLine={false} axisLine={false} /><Tooltip contentStyle={{ borderRadius: 12, fontSize: 12 }} formatter={(value: number) => [`${value} başvuru`, '']} /><Bar dataKey='count' radius={[0, 6, 6, 0]} className='fill-primary' /></BarChart>
                </ResponsiveContainer>
              )}
            </CardContent>
          </Card>
        </section>

        {scheduleCapacity.length > 0 && (
          <Card className='border-border/70'>
            <CardHeader className='pb-2'>
              <div className='flex items-center justify-between'>
                <div><CardTitle className='text-base'>Takvim Doluluk Oranları</CardTitle><CardDescription>Yaklaşan eğitimlerin kontenjan durumu (%)</CardDescription></div>
                <Button asChild variant='ghost' size='sm' className='h-7 rounded-lg text-xs'><Link to='/schedules'>Tümü <ArrowUpRight className='size-3' /></Link></Button>
              </div>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width='100%' height={200}>
                <AreaChart data={scheduleCapacity}><XAxis dataKey='name' tick={{ fontSize: 11 }} tickLine={false} axisLine={false} /><YAxis tick={{ fontSize: 11 }} tickLine={false} axisLine={false} domain={[0, 100]} tickFormatter={(v) => `${v}%`} /><Tooltip contentStyle={{ borderRadius: 12, fontSize: 12 }} formatter={(value: number) => [`%${value} dolu`, '']} /><Area type='monotone' dataKey='doluluk' stroke='#8b5cf6' fill='#8b5cf6' fillOpacity={0.15} strokeWidth={2} /></AreaChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        )}

        <section className='grid gap-6 lg:grid-cols-[1fr_1fr_0.8fr]'>
          <Card className='border-border/70'>
            <CardHeader className='pb-3'>
              <div className='flex items-center justify-between'><CardTitle className='text-base'>Son Başvurular</CardTitle><Button asChild variant='ghost' size='sm' className='h-7 rounded-lg text-xs'><Link to='/leads'>Tümü <ArrowUpRight className='size-3' /></Link></Button></div>
            </CardHeader>
            <CardContent className='space-y-1'>
              {leadsQ.isLoading ? (<LoadingPlaceholder />) : (leadsQ.data?.items ?? []).length === 0 ? (<EmptyPlaceholder text='Başvuru yok' />) : (
                (leadsQ.data?.items ?? []).map((lead) => (
                  <div key={lead.id} className='flex items-center gap-3 rounded-lg px-2 py-2 transition hover:bg-muted/50'>
                    <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-xs font-bold ${!lead.isRead ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'}`}>{lead.name.charAt(0).toUpperCase()}</div>
                    <div className='min-w-0 flex-1'><p className={`text-sm truncate ${!lead.isRead ? 'font-semibold' : ''}`}>{lead.name}</p><p className='text-[11px] text-muted-foreground truncate'>{lead.phone}{lead.targetCourse ? ` \u2014 ${lead.targetCourse}` : ''}</p></div>
                    <div className='flex shrink-0 flex-col items-end gap-1'><StatusDot status={lead.status} />{lead.createdAt && (<span className='text-[10px] text-muted-foreground'>{timeAgo(lead.createdAt)}</span>)}</div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          <Card className='border-border/70'>
            <CardHeader className='pb-3'>
              <div className='flex items-center justify-between'><CardTitle className='text-base'>Yaklaşan Eğitimler</CardTitle><Button asChild variant='ghost' size='sm' className='h-7 rounded-lg text-xs'><Link to='/schedules'>Tümü <ArrowUpRight className='size-3' /></Link></Button></div>
            </CardHeader>
            <CardContent className='space-y-2'>
              {schedulesQ.isLoading ? (<LoadingPlaceholder />) : (schedulesQ.data?.items ?? []).length === 0 ? (<EmptyPlaceholder text='Planlanmış eğitim yok' />) : (
                (schedulesQ.data?.items ?? []).slice(0, 5).map((s) => (
                  <div key={s.id} className='rounded-xl border border-border/60 bg-muted/20 p-3'>
                    <p className='text-sm font-medium truncate'>{s.courseTitle}</p>
                    <div className='mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground'>
                      <span className='flex items-center gap-1'><Clock className='size-3' />{s.startDate ? new Date(s.startDate).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' }) : '\u2014'}{s.endDate ? ` \u2014 ${new Date(s.endDate).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' })}` : ''}</span>
                      <span className='flex items-center gap-1'><MapPin className='size-3' />{s.location}</span>
                    </div>
                    <div className='mt-2 flex items-center justify-between'>
                      <div className='h-1.5 flex-1 overflow-hidden rounded-full bg-muted'>
                        <div className='h-full rounded-full transition-all' style={{ width: `${s.quota > 0 ? Math.min(((s.quota - s.availableSeats) / s.quota) * 100, 100) : 0}%`, backgroundColor: s.availableSeats <= 3 ? '#ef4444' : s.availableSeats <= s.quota * 0.3 ? '#f59e0b' : '#10b981' }} />
                      </div>
                      <span className='ml-3 text-[11px] font-medium tabular-nums'>{s.quota - s.availableSeats}/{s.quota}</span>
                    </div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>

          <div className='space-y-6'>
            <Card className='border-border/70'>
              <CardHeader className='pb-3'><CardTitle className='text-base'>Son Aktiviteler</CardTitle></CardHeader>
              <CardContent>
                {recentActivity.length === 0 ? (<EmptyPlaceholder text='Aktivite yok' />) : (
                  <div className='relative space-y-4 pl-6'>
                    <div className='absolute left-[11px] top-1 bottom-1 w-px bg-border' />
                    {recentActivity.map((item) => { const Icon = item.icon; return (
                      <div key={item.id} className='relative flex gap-3'>
                        <div className={`absolute -left-6 flex h-6 w-6 items-center justify-center rounded-full ${item.color}`}><Icon className='size-3' /></div>
                        <div className='min-w-0 pt-0.5'><p className='text-sm leading-snug'>{item.text}</p>{item.time && (<p className='text-[11px] text-muted-foreground'>{timeAgo(item.time)}</p>)}</div>
                      </div>
                    ) })}
                  </div>
                )}
              </CardContent>
            </Card>
            <Card className='border-border/70'>
              <CardHeader className='pb-3'><CardTitle className='text-base'>CMS Durumu</CardTitle></CardHeader>
              <CardContent className='space-y-2'>
                <CmsRow icon={Monitor} label='Hero Slider' count={heroSlidesQ.data?.meta.total ?? 0} href='/hero-slides' />
                <CmsRow icon={FileText} label='Sayfalar' count={pagesQ.data?.meta.total ?? 0} href='/pages' />
                <CmsRow icon={Activity} label='SSS' count={faqsQ.data?.meta.total ?? 0} href='/faqs' />
                <CmsRow icon={ShieldCheck} label='Roller' count={usersQ.data?.meta.total ?? 0} href='/roles' />
                <CmsRow icon={Settings} label='Ayarlar' count={0} href='/settings' badge='Düzenle' />
              </CardContent>
            </Card>
          </div>
        </section>

        <section>
          <h2 className='mb-3 text-sm font-semibold text-muted-foreground uppercase tracking-wider'>Hızlı Erişim</h2>
          <div className='grid gap-2 grid-cols-2 sm:grid-cols-3 lg:grid-cols-5'>
            {[
              { icon: BookOpen, label: 'Eğitimler', href: '/courses' },
              { icon: CalendarRange, label: 'Takvim', href: '/schedules' },
              { icon: Megaphone, label: 'Duyurular', href: '/announcements' },
              { icon: FileText, label: 'Sayfalar', href: '/pages' },
              { icon: Monitor, label: 'Hero Slider', href: '/hero-slides' },
              { icon: Mail, label: 'Başvurular', href: '/leads' },
              { icon: MessageSquare, label: 'Yorumlar', href: '/comments' },
              { icon: ShieldCheck, label: 'Roller', href: '/roles' },
              { icon: Users, label: 'Kullanıcılar', href: '/users' },
              { icon: Settings, label: 'Ayarlar', href: '/settings' },
            ].map((item) => (
              <Link key={item.href} to={item.href}>
                <div className='flex items-center gap-2.5 rounded-xl border border-border/60 bg-card px-3 py-2.5 text-sm transition hover:border-primary/30 hover:bg-muted/30'>
                  <item.icon className='size-4 shrink-0 text-muted-foreground' />
                  {item.label}
                </div>
              </Link>
            ))}
          </div>
        </section>
      </Main>
    </>
  )
}
