import {
  mdiArrowRight,
  mdiCalendarClock,
  mdiChartTimelineVariant,
  mdiCheckCircleOutline,
  mdiClockAlertOutline,
  mdiCurrencyUsd,
  mdiOpenInNew,
  mdiTarget,
} from '@mdi/js'
import axios from 'axios'
import Head from 'next/head'
import Link from 'next/link'
import React, { ReactElement, useEffect, useMemo, useState } from 'react'
import BaseButton from '../components/BaseButton'
import CardBox from '../components/CardBox'
import FormField from '../components/FormField'
import LayoutAuthenticated from '../layouts/Authenticated'
import NotificationBar from '../components/NotificationBar'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import { getPageTitle } from '../config'
import { useAppSelector } from '../stores/hooks'

type Stats = {
  myOpenLeads: number
  myActiveDeals: number
  dueToday: number
  overdue: number
  completedThisWeek: number
}

type FollowUpItem = {
  id: string
  subject: string
  status: string
  activityType: string
  dueAt: string | null
  relatedName: string
  relatedType: 'lead' | 'deal' | 'contact' | 'activity'
  relatedId: string | null
}

type RecentLead = {
  id: string
  title: string
  status: string
  estimatedValue: number | null
  nextFollowUpAt: string | null
  companyName: string | null
  stageName: string | null
}

type StageSummary = {
  id: string
  name: string
  dealCount: number
  amount: number
}

type QuickOption = {
  id: string
  label: string
}

type SalesHubResponse = {
  stats: Stats
  followUps: FollowUpItem[]
  recentLeads: RecentLead[]
  stageSummary: StageSummary[]
  quickOptions: {
    leads: QuickOption[]
    deals: QuickOption[]
    contacts: QuickOption[]
  }
}

type RelationType = 'lead' | 'deal' | 'contact'

type FollowUpForm = {
  subject: string
  activityType: string
  dueAt: string
  relationType: RelationType
  relationId: string
  details: string
}

const emptyHubData: SalesHubResponse = {
  stats: {
    myOpenLeads: 0,
    myActiveDeals: 0,
    dueToday: 0,
    overdue: 0,
    completedThisWeek: 0,
  },
  followUps: [],
  recentLeads: [],
  stageSummary: [],
  quickOptions: {
    leads: [],
    deals: [],
    contacts: [],
  },
}

const defaultForm: FollowUpForm = {
  subject: '',
  activityType: 'follow_up',
  dueAt: '',
  relationType: 'lead',
  relationId: '',
  details: '',
}

const relationLabels: Record<RelationType, string> = {
  lead: 'potansiyel müşteri',
  deal: 'fırsat',
  contact: 'kişi',
}

const relationPaths: Record<'lead' | 'deal' | 'contact', string> = {
  lead: '/leads',
  deal: '/deals',
  contact: '/contacts',
}

const activityTypeLabels: Record<string, string> = {
  call: 'Arama',
  email: 'E-posta',
  meeting: 'Toplantı',
  task: 'Görev',
  note: 'Not',
  demo: 'Demo',
  follow_up: 'Takip',
}

const statusLabels: Record<string, string> = {
  planned: 'Planlandı',
  done: 'Tamamlandı',
  canceled: 'İptal edildi',
  in_progress: 'Devam ediyor',
}

const statCards = [
  {
    key: 'myOpenLeads',
    label: 'Açık potansiyel müşteri',
    helper: 'Henüz nitelendirilmemiş veya sıradaki temas bekleyen kayıtlar.',
    icon: mdiTarget,
  },
  {
    key: 'myActiveDeals',
    label: 'Aktif fırsat',
    helper: 'Şu anda sizin sorumluluğunuzdaki fırsatlar.',
    icon: mdiCurrencyUsd,
  },
  {
    key: 'dueToday',
    label: 'Bugün aksiyon bekleyen',
    helper: 'Gün bitmeden dokunulması gereken takipler.',
    icon: mdiCalendarClock,
  },
  {
    key: 'overdue',
    label: 'Geciken',
    helper: 'Tarihi geçmiş ve momentum kaybetme riski taşıyan işler.',
    icon: mdiClockAlertOutline,
  },
] as const

const quickActionLinks = [
  {
    href: '/leads/leads-new',
    label: 'Yeni potansiyel müşteri',
    description: 'Sahibi belli yeni bir fırsatı ilk günden sisteme alın.',
  },
  {
    href: '/deals/deals-new',
    label: 'Yeni fırsat aç',
    description: 'Nitelenen işleri aktif pipeline içine taşıyın.',
  },
  {
    href: '/contacts/contacts-new',
    label: 'Yeni kişi ekle',
    description: 'Her fırsatın arkasındaki karar vericileri görünür tutun.',
  },
  {
    href: '/activities/activities-list',
    label: 'Tüm aktiviteler',
    description: 'Görev, toplantı, e-posta ve takiplerin tamamını inceleyin.',
  },
]

const formatCurrency = (value?: number | null) => {
  const amount = Number(value || 0)

  return new Intl.NumberFormat('tr-TR', {
    style: 'currency',
    currency: 'TRY',
    maximumFractionDigits: 0,
  }).format(amount)
}

const formatDateTime = (value?: string | null) => {
  if (!value) {
    return 'Termin yok'
  }

  return new Intl.DateTimeFormat('tr-TR', {
    day: '2-digit',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(value))
}

const getActivityTone = (dueAt?: string | null) => {
  if (!dueAt) {
    return 'bg-slate-100 text-slate-700 dark:bg-slate-900/70 dark:text-slate-300'
  }

  const dueDate = new Date(dueAt).getTime()
  const today = new Date()
  const startOfTomorrow = new Date(today)
  startOfTomorrow.setHours(24, 0, 0, 0)

  if (dueDate < Date.now()) {
    return 'bg-rose-100 text-rose-700 dark:bg-rose-950/50 dark:text-rose-300'
  }

  if (dueDate < startOfTomorrow.getTime()) {
    return 'bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300'
  }

  return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'
}

const SalesHub = () => {
  const { currentUser } = useAppSelector((state) => state.auth)
  const [hubData, setHubData] = useState<SalesHubResponse>(emptyHubData)
  const [loading, setLoading] = useState(true)
  const [loadingError, setLoadingError] = useState('')
  const [form, setForm] = useState<FollowUpForm>(defaultForm)
  const [formError, setFormError] = useState('')
  const [successState, setSuccessState] = useState<{ id: string; subject: string } | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const loadHub = async () => {
    try {
      setLoading(true)
      setLoadingError('')
      const { data } = await axios.get<SalesHubResponse>('/sales-hub')
      setHubData(data)
    } catch (error: any) {
      setLoadingError(
        error?.response?.data?.message || 'Satış merkezi yüklenemedi. Lütfen tekrar deneyin.',
      )
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (currentUser?.id) {
      loadHub()
    }
  }, [currentUser?.id])

  const relationOptions = useMemo(() => {
    return hubData.quickOptions[`${form.relationType}s` as keyof SalesHubResponse['quickOptions']] || []
  }, [form.relationType, hubData.quickOptions])

  useEffect(() => {
    if (!relationOptions.length) {
      setForm((currentForm) => ({
        ...currentForm,
        relationId: '',
      }))
      return
    }

    if (!relationOptions.find((option) => option.id === form.relationId)) {
      setForm((currentForm) => ({
        ...currentForm,
        relationId: relationOptions[0]?.id || '',
      }))
    }
  }, [relationOptions, form.relationId])

  const handleFormChange =
    (field: keyof FollowUpForm) =>
    (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
      const value = event.target.value
      setFormError('')
      setSuccessState(null)
      setForm((currentForm) => ({
        ...currentForm,
        [field]: value,
        ...(field === 'relationType' ? { relationId: '' } : {}),
      }))
    }

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setFormError('')
    setSuccessState(null)

    if (!form.subject.trim()) {
      setFormError('Takibin ne için açıldığını açıklayan kısa bir konu yazın.')
      return
    }

    if (!form.dueAt) {
      setFormError('Takip için bir tarih ve saat seçin.')
      return
    }

    if (!form.relationId) {
      setFormError(`Takibin bağlanacağı bir ${relationLabels[form.relationType]} seçin.`)
      return
    }

    try {
      setIsSubmitting(true)
      const { data } = await axios.post('/sales-hub/follow-ups', {
        data: {
          subject: form.subject.trim(),
          activity_type: form.activityType,
          due_at: new Date(form.dueAt).toISOString(),
          relationType: form.relationType,
          relationId: form.relationId,
          details: form.details.trim(),
        },
      })

      setSuccessState(data)
      setForm((currentForm) => ({
        ...defaultForm,
        relationType: currentForm.relationType,
      }))
      await loadHub()
    } catch (error: any) {
      setFormError(
        error?.response?.data?.message || 'Takip planlanamadı. Lütfen formu kontrol edip tekrar deneyin.',
      )
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Satış Merkezi')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title='Satış Merkezi' main>
          {''}
        </SectionTitleLineWithButton>

        <div className='grid gap-6'>
          <CardBox className='overflow-hidden border-slate-900 bg-gradient-to-br from-[#0b1020] via-[#13213d] to-[#1d4ed8] text-white shadow-2xl shadow-slate-950/20'>
            <div className='grid gap-8 lg:grid-cols-[1.4fr_0.9fr]'>
              <div className='space-y-5'>
                <div className='inline-flex items-center rounded-full border border-white/20 bg-white/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-cyan-100'>
                  DakikTabela · CRM operasyon odağı
                </div>
                <div className='space-y-3'>
                  <h2 className='text-3xl font-semibold tracking-tight md:text-4xl'>
                    Pipeline sorumluluğunu görün, sıradaki işi kaçırmayın, takip disiplinini koruyun.
                  </h2>
                  <p className='max-w-2xl text-sm leading-6 text-slate-200 md:text-base'>
                    Bu ekran günlük satış ritmini tek yerde toplar: size ait fırsatları inceleyin, geciken işleri
                    görün, yeni takip planlayın ve doğrudan ilgili kayda geçin.
                  </p>
                </div>
                <div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-4'>
                  {quickActionLinks.map((action) => (
                    <Link
                      key={action.href}
                      href={action.href}
                      className='group rounded-2xl border border-white/10 bg-white/10 p-4 transition hover:border-cyan-300/50 hover:bg-white/15'
                    >
                      <div className='flex items-center justify-between gap-3'>
                        <span className='font-semibold text-white'>{action.label}</span>
                        <span className='rounded-full bg-white/10 p-2 transition group-hover:bg-cyan-400/20'>
                          <svg viewBox='0 0 24 24' className='h-4 w-4 fill-current'>
                            <path d={mdiArrowRight} />
                          </svg>
                        </span>
                      </div>
                      <p className='mt-3 text-sm leading-6 text-slate-200'>{action.description}</p>
                    </Link>
                  ))}
                </div>
              </div>

              <div className='grid gap-3 rounded-3xl border border-white/10 bg-slate-950/25 p-5 backdrop-blur-sm'>
                <p className='text-sm font-semibold text-cyan-100'>Bugünün ritmi</p>
                <div className='space-y-4'>
                  <div>
                    <p className='text-4xl font-semibold'>{hubData.stats.completedThisWeek}</p>
                    <p className='mt-1 text-sm text-slate-200'>Bu hafta tamamlanan takip</p>
                  </div>
                  <div className='grid gap-3 sm:grid-cols-2 lg:grid-cols-1'>
                    <div className='rounded-2xl border border-white/10 bg-white/10 p-4'>
                      <p className='text-xs uppercase tracking-[0.2em] text-slate-300'>Önerilen aksiyon</p>
                      <p className='mt-2 font-medium'>Her lead ve fırsat için tarihli bir sonraki adım belirleyin.</p>
                    </div>
                    <div className='rounded-2xl border border-white/10 bg-white/10 p-4'>
                      <p className='text-xs uppercase tracking-[0.2em] text-slate-300'>İyi uygulama</p>
                      <p className='mt-2 font-medium'>Her takipte tek sahip, net konu ve kesin termin olsun.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </CardBox>

          {loadingError && (
            <NotificationBar color='danger'>
              <span>{loadingError}</span>
            </NotificationBar>
          )}

          {successState && (
            <NotificationBar
              color='success'
              button={
                <BaseButton
                  color='success'
                  href={`/activities/${successState.id}`}
                  label='Aktiviteyi aç'
                  icon={mdiOpenInNew}
                  small
                />
              }
            >
              <span>
                Takip planlandı: <strong>{successState.subject}</strong>
              </span>
            </NotificationBar>
          )}

          <div className='grid gap-6 xl:grid-cols-[1.45fr_0.95fr]'>
            <div className='space-y-6'>
              <div className='grid gap-4 md:grid-cols-2 xl:grid-cols-4'>
                {statCards.map((card) => (
                  <CardBox key={card.key} className='border-slate-200/70 bg-white/90 shadow-sm dark:border-dark-700'>
                    <div className='flex items-start justify-between gap-4'>
                      <div>
                        <p className='text-sm font-semibold text-slate-500 dark:text-slate-300'>{card.label}</p>
                        <p className='mt-3 text-4xl font-semibold text-slate-900 dark:text-white'>
                          {hubData.stats[card.key]}
                        </p>
                      </div>
                      <div className='rounded-2xl bg-slate-100 p-3 text-slate-700 dark:bg-slate-800 dark:text-slate-100'>
                        <svg viewBox='0 0 24 24' className='h-5 w-5 fill-current'>
                          <path d={card.icon} />
                        </svg>
                      </div>
                    </div>
                    <p className='mt-4 text-sm leading-6 text-slate-500 dark:text-slate-300'>{card.helper}</p>
                  </CardBox>
                ))}
              </div>

              <CardBox className='border-slate-200/70 bg-white/95 shadow-sm dark:border-dark-700'>
                <div className='flex flex-col gap-3 border-b border-slate-200 pb-4 dark:border-dark-700 md:flex-row md:items-end md:justify-between'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-cyan-600 dark:text-cyan-300'>
                      Öncelikli işler
                    </p>
                    <h3 className='mt-1 text-2xl font-semibold text-slate-900 dark:text-white'>Takip kuyruğum</h3>
                    <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                      Size atanan sıradaki aktiviteler burada listelenir. Aktiviteyi veya bağlı kaydı tek tıkla açabilirsiniz.
                    </p>
                  </div>
                  <BaseButton color='info' href='/activities/activities-list' label='Tüm aktiviteler' small />
                </div>

                {loading ? (
                  <div className='grid gap-3 py-6'>
                    {Array.from({ length: 4 }).map((_, index) => (
                      <div key={index} className='h-24 animate-pulse rounded-2xl bg-slate-100 dark:bg-slate-800' />
                    ))}
                  </div>
                ) : hubData.followUps.length ? (
                  <div className='grid gap-3 pt-6'>
                    {hubData.followUps.map((item) => {
                      const relatedPath =
                        item.relatedType !== 'activity' && item.relatedId
                          ? `${relationPaths[item.relatedType]}/${item.relatedId}`
                          : null

                      return (
                        <div
                          key={item.id}
                          className='grid gap-3 rounded-2xl border border-slate-200/80 bg-slate-50/70 p-4 dark:border-dark-700 dark:bg-dark-900/50 lg:grid-cols-[1.2fr_0.9fr_auto] lg:items-center'
                        >
                          <div>
                            <div className='flex flex-wrap items-center gap-2'>
                              <span className={`rounded-full px-2.5 py-1 text-xs font-semibold ${getActivityTone(item.dueAt)}`}>
                                {formatDateTime(item.dueAt)}
                              </span>
                              <span className='rounded-full bg-slate-900 px-2.5 py-1 text-xs font-semibold uppercase tracking-wide text-white dark:bg-slate-100 dark:text-slate-900'>
                                {activityTypeLabels[item.activityType] || item.activityType}
                              </span>
                            </div>
                            <h4 className='mt-3 text-lg font-semibold text-slate-900 dark:text-white'>{item.subject}</h4>
                            <p className='mt-1 text-sm text-slate-500 dark:text-slate-300'>Bağlı kayıt: {item.relatedName}</p>
                          </div>
                          <div className='text-sm text-slate-500 dark:text-slate-300'>
                            <p className='font-medium text-slate-900 dark:text-white'>
                              Durum: {statusLabels[item.status] || item.status.replace('_', ' ')}
                            </p>
                            <p className='mt-1'>Termin kaymadan önce sıradaki teması tamamlayın.</p>
                          </div>
                          <div className='flex flex-wrap gap-2 lg:justify-end'>
                            <BaseButton color='info' href={`/activities/${item.id}`} label='Aktivite detayı' small />
                            {relatedPath && (
                              <BaseButton color='white' outline href={relatedPath} label='Kaydı aç' small />
                            )}
                          </div>
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <div className='rounded-2xl border border-dashed border-slate-300 bg-slate-50/70 px-6 py-8 text-center dark:border-dark-600 dark:bg-dark-900/50'>
                    <p className='text-lg font-semibold text-slate-900 dark:text-white'>Size atanmış bekleyen takip yok.</p>
                    <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                      Yeni bir takip planlayabilir veya aktivite listesinden tamamlanan işleri gözden geçirebilirsiniz.
                    </p>
                  </div>
                )}
              </CardBox>

              <CardBox className='border-slate-200/70 bg-white/95 shadow-sm dark:border-dark-700'>
                <div className='flex flex-col gap-3 border-b border-slate-200 pb-4 dark:border-dark-700 md:flex-row md:items-end md:justify-between'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-cyan-600 dark:text-cyan-300'>
                      Yeni akış
                    </p>
                    <h3 className='mt-1 text-2xl font-semibold text-slate-900 dark:text-white'>Son potansiyel müşteriler</h3>
                  </div>
                  <BaseButton color='info' href='/leads/leads-list' label='Lead listesini aç' small />
                </div>
                {loading ? (
                  <div className='grid gap-3 py-6'>
                    {Array.from({ length: 3 }).map((_, index) => (
                      <div key={index} className='h-20 animate-pulse rounded-2xl bg-slate-100 dark:bg-slate-800' />
                    ))}
                  </div>
                ) : hubData.recentLeads.length ? (
                  <div className='grid gap-3 pt-6'>
                    {hubData.recentLeads.map((lead) => (
                      <Link
                        key={lead.id}
                        href={`/leads/${lead.id}`}
                        className='grid gap-3 rounded-2xl border border-slate-200/80 bg-slate-50/70 p-4 transition hover:border-cyan-300 hover:bg-white dark:border-dark-700 dark:bg-dark-900/50 dark:hover:border-cyan-500 lg:grid-cols-[1.1fr_0.9fr_auto] lg:items-center'
                      >
                        <div>
                          <p className='text-lg font-semibold text-slate-900 dark:text-white'>{lead.title}</p>
                          <p className='mt-1 text-sm text-slate-500 dark:text-slate-300'>
                            {lead.companyName || 'Şirket bağlı değil'} · {lead.stageName || 'Aşama seçilmedi'}
                          </p>
                        </div>
                        <div className='text-sm text-slate-500 dark:text-slate-300'>
                          <p className='font-medium text-slate-900 dark:text-white'>{formatCurrency(lead.estimatedValue)}</p>
                          <p className='mt-1'>Sonraki temas: {formatDateTime(lead.nextFollowUpAt)}</p>
                        </div>
                        <div className='justify-self-start rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-white dark:bg-slate-100 dark:text-slate-900'>
                          {lead.status}
                        </div>
                      </Link>
                    ))}
                  </div>
                ) : (
                  <div className='rounded-2xl border border-dashed border-slate-300 bg-slate-50/70 px-6 py-8 text-center dark:border-dark-600 dark:bg-dark-900/50'>
                    <p className='text-lg font-semibold text-slate-900 dark:text-white'>Henüz aktif potansiyel müşteri yok.</p>
                    <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                      İlk lead kaydınızı oluşturduğunuzda bu alanda yeni akış görünmeye başlar.
                    </p>
                    <div className='mt-5 flex justify-center'>
                      <BaseButton color='info' href='/leads/leads-new' label='İlk lead kaydını oluştur' />
                    </div>
                  </div>
                )}
              </CardBox>
            </div>

            <div className='space-y-6'>
              <CardBox className='border-slate-200/70 bg-white/95 shadow-sm dark:border-dark-700'>
                <div className='border-b border-slate-200 pb-4 dark:border-dark-700'>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-cyan-600 dark:text-cyan-300'>
                    Planlı aksiyon
                  </p>
                  <h3 className='mt-1 text-2xl font-semibold text-slate-900 dark:text-white'>Yeni takip planla</h3>
                  <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                    Takibi bir lead, fırsat veya kişiye bağlayın; konu, tarih ve not ile ekipteki sorumluluğu netleştirin.
                  </p>
                </div>

                <form className='pt-6' onSubmit={handleSubmit}>
                  <FormField label='Konu' help='Takibin neden açıldığını kısa ve net yazın.'>
                    <input value={form.subject} onChange={handleFormChange('subject')} placeholder='Örn. teklif sonrası arama' />
                  </FormField>

                  <div className='grid gap-4 md:grid-cols-2'>
                    <FormField label='Takip tipi' help='Bu kaydın nasıl ilerletileceğini seçin.'>
                      <select value={form.activityType} onChange={handleFormChange('activityType')}>
                        {Object.entries(activityTypeLabels).map(([value, label]) => (
                          <option key={value} value={value}>
                            {label}
                          </option>
                        ))}
                      </select>
                    </FormField>

                    <FormField label='Termin' help='Takibin tamamlanması gereken tarih ve saat.'>
                      <input type='datetime-local' value={form.dueAt} onChange={handleFormChange('dueAt')} />
                    </FormField>
                  </div>

                  <FormField label='Bağlı kayıt tipi' help='Takibin bağlanacağı kayıt türünü seçin.'>
                    <select value={form.relationType} onChange={handleFormChange('relationType')}>
                      <option value='lead'>Potansiyel müşteri</option>
                      <option value='deal'>Fırsat</option>
                      <option value='contact'>Kişi</option>
                    </select>
                  </FormField>

                  <FormField
                    label='Bağlı kayıt'
                    help={`Sadece size açık olan ${relationLabels[form.relationType]} kayıtları burada görünür.`}
                  >
                    <select value={form.relationId} onChange={handleFormChange('relationId')}>
                      <option value=''>Kayıt seçin</option>
                      {relationOptions.map((option) => (
                        <option key={option.id} value={option.id}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                  </FormField>

                  {!relationOptions.length && (
                    <div className='mb-6 rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-4 text-sm text-slate-600 dark:border-dark-600 dark:bg-dark-900/50 dark:text-slate-300'>
                      Önce bir {relationLabels[form.relationType]} oluşturun veya size atanmış kayıtları güncelleyin; ardından bu alanda seçim yapabilirsiniz.
                    </div>
                  )}

                  <FormField label='Notlar' help='Bir sonraki temas için gerekli bağlam, risk veya beklentiyi yazın.'>
                    <textarea
                      value={form.details}
                      onChange={handleFormChange('details')}
                      placeholder='Örn. fiyat itirazı var, revize teklif gönderildikten sonra aranacak.'
                    />
                  </FormField>

                  {formError && (
                    <NotificationBar color='danger'>
                      <span>{formError}</span>
                    </NotificationBar>
                  )}

                  <div className='flex flex-wrap gap-3'>
                    <BaseButton
                      type='submit'
                      color='info'
                      label={isSubmitting ? 'Planlanıyor…' : 'Takibi planla'}
                      icon={mdiCheckCircleOutline}
                      disabled={isSubmitting}
                    />
                    <BaseButton color='white' outline label='Aktivite listesine git' href='/activities/activities-list' />
                  </div>
                </form>
              </CardBox>

              <CardBox className='border-slate-200/70 bg-white/95 shadow-sm dark:border-dark-700'>
                <div className='border-b border-slate-200 pb-4 dark:border-dark-700'>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-cyan-600 dark:text-cyan-300'>Özet görünüm</p>
                  <h3 className='mt-1 text-2xl font-semibold text-slate-900 dark:text-white'>Aşamaya göre fırsatlar</h3>
                  <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                    Aktif pipeline&apos;ı aşama ve toplam değer bazında görün; satış ritmini günlük ekranınızdan takip edin.
                  </p>
                </div>
                {loading ? (
                  <div className='grid gap-3 py-6'>
                    {Array.from({ length: 4 }).map((_, index) => (
                      <div key={index} className='h-16 animate-pulse rounded-2xl bg-slate-100 dark:bg-slate-800' />
                    ))}
                  </div>
                ) : hubData.stageSummary.length ? (
                  <div className='grid gap-3 pt-6'>
                    {hubData.stageSummary.map((stage) => (
                      <div
                        key={stage.id}
                        className='rounded-2xl border border-slate-200/80 bg-slate-50/70 p-4 dark:border-dark-700 dark:bg-dark-900/50'
                      >
                        <div className='flex items-center justify-between gap-4'>
                          <div>
                            <p className='font-semibold text-slate-900 dark:text-white'>{stage.name}</p>
                            <p className='mt-1 text-sm text-slate-500 dark:text-slate-300'>
                              {stage.dealCount} aktif {stage.dealCount === 1 ? 'fırsat' : 'fırsat'}
                            </p>
                          </div>
                          <div className='text-right'>
                            <p className='font-semibold text-slate-900 dark:text-white'>{formatCurrency(stage.amount)}</p>
                            <p className='mt-1 text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400'>
                              toplam pipeline
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className='rounded-2xl border border-dashed border-slate-300 bg-slate-50/70 px-6 py-8 text-center dark:border-dark-600 dark:bg-dark-900/50'>
                    <p className='text-lg font-semibold text-slate-900 dark:text-white'>Henüz açık fırsat yok.</p>
                    <p className='mt-2 text-sm leading-6 text-slate-500 dark:text-slate-300'>
                      Fırsatlar aktif hale geldiğinde bu alan aşama dağılımını ve toplam değeri gösterecek.
                    </p>
                    <div className='mt-5 flex justify-center'>
                      <BaseButton color='info' href='/deals/deals-new' label='İlk fırsatı oluştur' />
                    </div>
                  </div>
                )}
              </CardBox>
            </div>
          </div>
        </div>
      </SectionMain>
    </>
  )
}

SalesHub.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}

export default SalesHub
