import {
  mdiAccountArrowRight,
  mdiAccountGroup,
  mdiArrowRight,
  mdiCalendarCheck,
  mdiCalendarStar,
  mdiChartTimelineVariant,
  mdiFormatListChecks,
  mdiClipboardSearch,
  mdiCubeOutline,
  mdiCurrencyUsd,
  mdiDomain,
  mdiFactory,
  mdiHandshake,
  mdiMapMarkerRadius,
  mdiPackageVariantClosed,
  mdiRobotIndustrial,
  mdiWarehouse,
} from '@mdi/js'
import axios from 'axios'
import Head from 'next/head'
import React from 'react'
import type { ReactElement } from 'react'
import BaseButton from '../components/BaseButton'
import BaseIcon from '../components/BaseIcon'
import CardBox from '../components/CardBox'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import { SmartWidget } from '../components/SmartWidget/SmartWidget'
import { WidgetCreator } from '../components/WidgetCreator/WidgetCreator'
import { getPageTitle } from '../config'
import { hasPermission } from '../helpers/userPermissions'
import LayoutAuthenticated from '../layouts/Authenticated'
import { fetchWidgets } from '../stores/roles/rolesSlice'
import { useAppDispatch, useAppSelector } from '../stores/hooks'

type CountValue = number | string | null

type CountItem = {
  key: string
  label: string
  href: string
  permission: string
  icon: string
}

type PlatformSection = {
  id: string
  title: string
  description: string
  href: string
  accent: string
  accentSoft: string
  items: CountItem[]
}

const loadingMessage = 'Yükleniyor...'

const crmItems: CountItem[] = [
  {
    key: 'companies',
    label: 'Şirketler',
    href: '/companies/companies-list',
    permission: 'READ_COMPANIES',
    icon: mdiDomain,
  },
  {
    key: 'leads',
    label: 'Potansiyel müşteriler',
    href: '/leads/leads-list',
    permission: 'READ_LEADS',
    icon: mdiAccountArrowRight,
  },
  {
    key: 'deals',
    label: 'Fırsatlar',
    href: '/deals/deals-list',
    permission: 'READ_DEALS',
    icon: mdiHandshake,
  },
  {
    key: 'activities',
    label: 'Aktiviteler',
    href: '/activities/activities-list',
    permission: 'READ_ACTIVITIES',
    icon: mdiCalendarCheck,
  },
]

const erpItems: CountItem[] = [
  {
    key: 'materials',
    label: 'Malzemeler',
    href: '/materials/materials-list',
    permission: 'READ_MATERIALS',
    icon: mdiCubeOutline,
  },
  {
    key: 'warehouses',
    label: 'Depolar',
    href: '/warehouses/warehouses-list',
    permission: 'READ_WAREHOUSES',
    icon: mdiWarehouse,
  },
  {
    key: 'inventory_items',
    label: 'Stok kalemleri',
    href: '/inventory_items/inventory_items-list',
    permission: 'READ_INVENTORY_ITEMS',
    icon: mdiPackageVariantClosed,
  },
  {
    key: 'machines',
    label: 'Makineler',
    href: '/machines/machines-list',
    permission: 'READ_MACHINES',
    icon: mdiRobotIndustrial,
  },
  {
    key: 'production_orders',
    label: 'Üretim emirleri',
    href: '/production_orders/production_orders-list',
    permission: 'READ_PRODUCTION_ORDERS',
    icon: mdiFactory,
  },
  {
    key: 'quality_inspections',
    label: 'Kalite kontrolleri',
    href: '/quality_inspections/quality_inspections-list',
    permission: 'READ_QUALITY_INSPECTIONS',
    icon: mdiClipboardSearch,
  },
]

const eventItems: CountItem[] = [
  {
    key: 'venues',
    label: 'Mekanlar',
    href: '/venues/venues-list',
    permission: 'READ_VENUES',
    icon: mdiMapMarkerRadius,
  },
  {
    key: 'events',
    label: 'Etkinlikler',
    href: '/events/events-list',
    permission: 'READ_EVENTS',
    icon: mdiCalendarStar,
  },
  {
    key: 'event_tasks',
    label: 'Etkinlik görevleri',
    href: '/event_tasks/event_tasks-list',
    permission: 'READ_EVENT_TASKS',
    icon: mdiFormatListChecks,
  },
  {
    key: 'event_guests',
    label: 'Davetliler',
    href: '/event_guests/event_guests-list',
    permission: 'READ_EVENT_GUESTS',
    icon: mdiAccountGroup,
  },
]

const platformSections: PlatformSection[] = [
  {
    id: 'crm',
    title: 'CRM ve Satış',
    description:
      'Teklif, fırsat ve müşteri takibini aynı akış içinde yönetin. Satış ekibi gününe takip kuyruğuyla başlasın.',
    href: '/sales-hub',
    accent: 'text-blue-700 dark:text-blue-300',
    accentSoft: 'bg-blue-50 dark:bg-blue-950/40',
    items: crmItems,
  },
  {
    id: 'erp',
    title: 'Üretim ERP',
    description:
      'Malzeme, stok, üretim emri ve kalite kontrollerini tek merkezden görün. Operasyon ve saha aynı veride buluşsun.',
    href: '/production_orders/production_orders-list',
    accent: 'text-teal-700 dark:text-teal-300',
    accentSoft: 'bg-teal-50 dark:bg-teal-950/40',
    items: erpItems,
  },
  {
    id: 'events',
    title: 'Etkinlik Yönetimi',
    description:
      'Mekan, davetli, görev ve bütçe kalemlerini uçtan uca planlayın. Saha organizasyonları görünür ve ölçülebilir olsun.',
    href: '/events/events-list',
    accent: 'text-amber-700 dark:text-amber-300',
    accentSoft: 'bg-amber-50 dark:bg-amber-950/40',
    items: eventItems,
  },
]

const quickActionLinks = [
  {
    href: '/sales-hub',
    label: 'Satış merkezini aç',
    description: 'Geciken takipleri, aktif fırsatları ve yeni temas planlarını tek ekranda yönetin.',
  },
  {
    href: '/production_orders/production_orders-new',
    label: 'Yeni üretim emri',
    description: 'Atölye planını güncellemek için yeni üretim emrini hızlıca sisteme kaydedin.',
  },
  {
    href: '/events/events-new',
    label: 'Yeni etkinlik oluştur',
    description: 'Saha uygulamaları, açılışlar veya müşteri etkinliklerini kayıt altına alın.',
  },
  {
    href: '/search',
    label: 'Platform genelinde ara',
    description: 'DakikTabela verilerinde şirket, kişi, stok veya etkinlik kaydı arayın.',
  },
]

const formatCount = (value: CountValue) => {
  if (typeof value === 'number') {
    return value.toLocaleString('tr-TR')
  }

  if (typeof value === 'string') {
    return value
  }

  return '—'
}

const Dashboard = () => {
  const dispatch = useAppDispatch()
  const { currentUser } = useAppSelector((state) => state.auth)
  const { isFetchingQuery } = useAppSelector((state) => state.openAi)
  const { rolesWidgets, loading } = useAppSelector((state) => state.roles)
  const iconsColor = useAppSelector((state) => state.style.iconsColor)
  const corners = useAppSelector((state) => state.style.corners)

  const [counts, setCounts] = React.useState<Record<string, CountValue>>(() => {
    const initialState: Record<string, CountValue> = {}

    ;[...crmItems, ...erpItems, ...eventItems].forEach((item) => {
      initialState[item.key] = loadingMessage
    })

    return initialState
  })

  const [widgetsRole, setWidgetsRole] = React.useState({
    role: { value: '', label: '' },
  })

  const loadCounts = React.useCallback(async () => {
    if (!currentUser) {
      return
    }

    const allItems = [...crmItems, ...erpItems, ...eventItems]
    const nextCounts: Record<string, CountValue> = {}

    allItems.forEach((item) => {
      nextCounts[item.key] = hasPermission(currentUser, item.permission) ? loadingMessage : null
    })

    setCounts(nextCounts)

    const requests = allItems.map(async (item) => {
      if (!hasPermission(currentUser, item.permission)) {
        return { key: item.key, value: null as CountValue }
      }

      try {
        const response = await axios.get(`/${item.key}/count`)
        return { key: item.key, value: response.data.count as number }
      } catch (error: any) {
        return { key: item.key, value: error?.message || 'Hata' }
      }
    })

    const results = await Promise.all(requests)

    setCounts((prev) =>
      results.reduce(
        (acc, item) => ({
          ...acc,
          [item.key]: item.value,
        }),
        prev,
      ),
    )
  }, [currentUser])

  React.useEffect(() => {
    if (!currentUser) {
      return
    }

    loadCounts().then()
    setWidgetsRole({
      role: {
        value: currentUser?.app_role?.id || '',
        label: currentUser?.app_role?.name || '',
      },
    })
  }, [currentUser, loadCounts])

  React.useEffect(() => {
    if (!currentUser || !widgetsRole?.role?.value) {
      return
    }

    dispatch(fetchWidgets(widgetsRole.role.value)).then()
  }, [currentUser, dispatch, widgetsRole?.role?.value])

  return (
    <>
      <Head>
        <title>{getPageTitle('Operasyon Özeti')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title='Operasyon Özeti' main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className='mb-6 overflow-hidden border border-slate-200/70 bg-gradient-to-br from-slate-950 via-blue-900 to-cyan-800 text-white shadow-xl'>
          <div className='grid gap-6 lg:grid-cols-[1.7fr_1fr]'>
            <div className='space-y-4 p-6 md:p-8'>
              <p className='text-sm uppercase tracking-[0.3em] text-slate-200/80'>DakikTabela</p>
              <div>
                <h2 className='text-3xl font-semibold leading-tight md:text-4xl'>
                  Tüm operasyonlarınızı tek ekranda yönetin.
                </h2>
                <p className='mt-3 max-w-2xl text-sm leading-7 text-slate-100/85 md:text-base'>
                  CRM ve satış, üretim ERP, etkinlik planlama ve yönetim modülleri DakikTabela için tek
                  bir operasyon omurgasında birleşiyor. Ekipler aynı veriyle hareket eder, süreçler daha
                  hızlı görünür hale gelir.
                </p>
              </div>
              <div className='flex flex-wrap gap-3'>
                <BaseButton href='/sales-hub' color='info' label='Satış merkezine git' />
                <BaseButton
                  href='/production_orders/production_orders-list'
                  color='warning'
                  outline
                  label='Üretim emirlerini aç'
                />
              </div>
            </div>
            <div className='grid gap-4 p-6 md:p-8'>
              <div className='rounded-3xl border border-white/10 bg-white/10 p-5 backdrop-blur'>
                <div className='text-sm text-slate-200'>Aktif rol</div>
                <div className='mt-2 text-2xl font-semibold'>{currentUser?.app_role?.name || 'Tanımsız rol'}</div>
              </div>
              <div className='rounded-3xl border border-white/10 bg-white/10 p-5 backdrop-blur'>
                <div className='text-sm text-slate-200'>Kullanıcı</div>
                <div className='mt-2 text-2xl font-semibold'>
                  {currentUser?.firstName || currentUser?.email || 'DakikTabela kullanıcısı'}
                </div>
              </div>
              <div className='rounded-3xl border border-white/10 bg-white/10 p-5 backdrop-blur'>
                <div className='text-sm text-slate-200'>Hazır iş alanları</div>
                <div className='mt-2 text-2xl font-semibold'>CRM • ERP • Etkinlik</div>
              </div>
            </div>
          </div>
        </CardBox>

        <div className='mb-6 grid gap-6 xl:grid-cols-3'>
          {platformSections.map((section) => {
            const visibleItems = section.items.filter((item) => hasPermission(currentUser, item.permission))

            if (!visibleItems.length) {
              return null
            }

            return (
              <CardBox key={section.id} className='h-full border border-slate-200/80'>
                <div className='flex h-full flex-col gap-5 p-1'>
                  <div className={`rounded-3xl px-5 py-4 ${section.accentSoft}`}>
                    <div className='flex items-start justify-between gap-4'>
                      <div>
                        <h2 className={`text-xl font-semibold ${section.accent}`}>{section.title}</h2>
                        <p className='mt-2 text-sm leading-6 text-slate-600 dark:text-slate-300'>
                          {section.description}
                        </p>
                      </div>
                      <BaseButton href={section.href} color='whiteDark' icon={mdiArrowRight} roundedFull />
                    </div>
                  </div>

                  <div className='grid gap-4 sm:grid-cols-2'>
                    {visibleItems.map((item) => (
                      <a
                        key={item.key}
                        href={item.href}
                        className={`flex items-center gap-4 border border-slate-200/70 bg-white p-4 transition hover:-translate-y-0.5 hover:border-blue-300 dark:border-dark-700 dark:bg-dark-900 ${
                          corners !== 'rounded-full' ? corners : 'rounded-3xl'
                        }`}
                      >
                        <div className='flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-100 dark:bg-slate-800'>
                          <BaseIcon className={iconsColor} path={item.icon} size={26} w='w-6' h='h-6' />
                        </div>
                        <div>
                          <div className='text-xs uppercase tracking-wide text-slate-500 dark:text-slate-400'>
                            {item.label}
                          </div>
                          <div className='mt-1 text-2xl font-semibold text-slate-900 dark:text-white'>
                            {formatCount(counts[item.key])}
                          </div>
                        </div>
                      </a>
                    ))}
                  </div>
                </div>
              </CardBox>
            )
          })}
        </div>

        <div className='mb-6 grid gap-6 lg:grid-cols-[1.4fr_1fr]'>
          <CardBox className='border border-slate-200/80'>
            <div className='p-1'>
              <div className='mb-4 flex items-center justify-between'>
                <div>
                  <h2 className='text-xl font-semibold text-slate-900 dark:text-white'>Hazır aksiyonlar</h2>
                  <p className='mt-1 text-sm text-slate-500 dark:text-slate-400'>
                    DakikTabela ekibinin en sık kullandığı operasyon giriş noktaları.
                  </p>
                </div>
              </div>
              <div className='grid gap-4'>
                {quickActionLinks.map((action) => (
                  <div
                    key={action.href}
                    className={`flex items-center justify-between gap-4 border border-slate-200/70 p-4 dark:border-dark-700 ${
                      corners !== 'rounded-full' ? corners : 'rounded-3xl'
                    }`}
                  >
                    <div>
                      <div className='font-semibold text-slate-900 dark:text-white'>{action.label}</div>
                      <div className='mt-1 text-sm text-slate-500 dark:text-slate-400'>{action.description}</div>
                    </div>
                    <BaseButton href={action.href} color='info' label='Aç' />
                  </div>
                ))}
              </div>
            </div>
          </CardBox>

          <CardBox className='border border-slate-200/80'>
            <div className='space-y-4 p-1'>
              <div>
                <h2 className='text-xl font-semibold text-slate-900 dark:text-white'>Yönetim görünürlüğü</h2>
                <p className='mt-1 text-sm text-slate-500 dark:text-slate-400'>
                  Kullanıcı, rol ve organizasyon yönetimine hızlı erişin.
                </p>
              </div>
              <div className='grid gap-3'>
                {[
                  { href: '/users/users-list', label: 'Kullanıcılar', permission: 'READ_USERS' },
                  { href: '/roles/roles-list', label: 'Roller', permission: 'READ_ROLES' },
                  { href: '/organizations/organizations-list', label: 'Organizasyonlar', permission: 'READ_ORGANIZATIONS' },
                ]
                  .filter((item) => hasPermission(currentUser, item.permission))
                  .map((item) => (
                    <BaseButton key={item.href} href={item.href} color='whiteDark' label={item.label} className='justify-start' />
                  ))}
              </div>
            </div>
          </CardBox>
        </div>

        {hasPermission(currentUser, 'CREATE_ROLES') && (
          <WidgetCreator
            currentUser={currentUser}
            isFetchingQuery={isFetchingQuery}
            setWidgetsRole={setWidgetsRole}
            widgetsRole={widgetsRole}
          />
        )}

        {!!rolesWidgets?.length && (
          <div className='grid grid-cols-2 gap-6'>
            {rolesWidgets.map((widget) => (
              <SmartWidget
                key={widget.widget_id}
                widget={widget}
                userId={currentUser?.id}
                admin={hasPermission(currentUser, 'CREATE_ROLES')}
                roleId={widgetsRole?.role?.value}
              />
            ))}
          </div>
        )}

        {!rolesWidgets?.length && !loading && (
          <CardBox className='border border-dashed border-slate-300 bg-slate-50/70 dark:border-slate-700 dark:bg-slate-900/50'>
            <div className='flex items-center justify-between gap-4'>
              <div>
                <h3 className='text-lg font-semibold text-slate-900 dark:text-white'>Akıllı gösterge paneli hazır</h3>
                <p className='mt-1 text-sm text-slate-500 dark:text-slate-400'>
                  Rol bazlı özel KPI veya grafik üretmek için yukarıdaki bileşen oluşturucuyu kullanın.
                </p>
              </div>
              <BaseButton href='/sales-hub' color='info' label='Satış merkezine dön' />
            </div>
          </CardBox>
        )}
      </SectionMain>
    </>
  )
}

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

export default Dashboard
