import React, { useEffect, useState } from 'react'
import Head from 'next/head'
import axios from 'axios'
import {
  mdiAccountMultiple,
  mdiCartOutline,
  mdiChartTimelineVariant,
  mdiShieldCheck,
  mdiStore,
  mdiCalendarRange,
  mdiCurrencyUsd,
  mdiAlertCircle
} from '@mdi/js'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import CardBox from '../components/CardBox'
import CardBoxComponentTitle from '../components/CardBoxComponentTitle'
import BaseIcon from '../components/BaseIcon'
import IconRounded from '../components/IconRounded'
import Link from 'next/link'
import LayoutAuthenticated from '../layouts/Authenticated'
import { getPageTitle } from '../config'
import { useAppSelector } from '../stores/hooks'
import { ColorKey } from '../interfaces'

type CardBoxWidgetProps = {
  number: number | string
  icon: string
  label: string
  title: string
  textColor: string
  color: ColorKey
}

const CardBoxWidget = (props: CardBoxWidgetProps) => {
  return (
    <CardBox>
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg leading-tight text-slate-500 dark:text-slate-400">
            {props.title}
          </h3>
          <h1 className="text-3xl leading-tight font-semibold">
            {props.number}
          </h1>
          <p className="text-sm text-slate-500 dark:text-slate-400">
            {props.label}
          </p>
        </div>
        <IconRounded icon={props.icon} color={props.color} bg />
      </div>
    </CardBox>
  )
}

const Dashboard = () => {
  const { currentUser } = useAppSelector((state) => state.auth)
  const [dashboardData, setDashboardData] = useState<any>(null)
  const [isFetching, setIsFetching] = useState(false)
  
  const isBusinessOwner = currentUser?.app_role?.name === 'Verified Business Owner'

  useEffect(() => {
    const fetchDashboard = async () => {
      setIsFetching(true)
      try {
        const response = await axios.get('/dashboard')
        setDashboardData(response.data)
      } catch (error) {
        console.error('Error fetching dashboard data:', error)
      } finally {
        setIsFetching(false)
      }
    }

    fetchDashboard()
  }, [])

  const stats = [
    {
      title: 'Total Views',
      icon: mdiChartTimelineVariant,
      number: dashboardData?.totalViews || 0,
      label: 'Overall visibility',
      color: 'success' as ColorKey,
    },
    {
      title: 'Active Leads',
      icon: mdiCartOutline,
      number: dashboardData?.activeLeads || 0,
      label: 'Potential clients',
      color: 'info' as ColorKey,
    },
    {
      title: 'Conversion Rate',
      icon: mdiShieldCheck,
      number: dashboardData?.conversionRate ? `${dashboardData.conversionRate}%` : '0%',
      label: 'Leads to jobs',
      color: 'warning' as ColorKey,
    },
  ]

  const adminStats = [
    {
      title: 'Active Users',
      icon: mdiAccountMultiple,
      number: dashboardData?.totalUsers || 0,
      label: 'Verified members',
      color: 'success' as ColorKey,
    },
    {
      title: 'Total Businesses',
      icon: mdiStore,
      number: dashboardData?.totalBusinesses || 0,
      label: 'Listed companies',
      color: 'info' as ColorKey,
    },
    {
      title: 'Revenue Flow',
      icon: mdiCurrencyUsd,
      number: dashboardData?.totalRevenue ? `$${dashboardData.totalRevenue.toLocaleString()}` : '$0',
      label: 'Network throughput',
      color: 'warning' as ColorKey,
    },
  ]

  return (
    <>
      <Head>
        <title>{getPageTitle('Dashboard')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={isBusinessOwner ? 'Business Performance' : 'Network Overview'}
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6">
          {(isBusinessOwner ? stats : adminStats).map((stat, index) => (
            <CardBoxWidget
              key={index}
              color={stat.color}
              textColor={''}
              icon={stat.icon}
              number={stat.number}
              label={stat.label}
              title={stat.title}
            />
          ))}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Quick Actions */}
          <CardBox className="h-full">
            <CardBoxComponentTitle title="Quick Operations" />
            <div className="grid grid-cols-2 gap-4">
              {isBusinessOwner ? (
                <>
                  <Link href="/businesses/businesses-new" className="p-4 rounded-2xl bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800 hover:shadow-lg transition-all text-center">
                    <BaseIcon path={mdiStore} size={32} className="text-emerald-500 mx-auto mb-2" />
                    <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Add Business</span>
                  </Link>
                  <Link href="/leads/leads-list" className="p-4 rounded-2xl bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800 hover:shadow-lg transition-all text-center">
                    <BaseIcon path={mdiCartOutline} size={32} className="text-blue-500 mx-auto mb-2" />
                    <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Manage Leads</span>
                  </Link>
                </>
              ) : (
                <>
                  <Link href="/users/users-list" className="p-4 rounded-2xl bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800 hover:shadow-lg transition-all text-center">
                    <BaseIcon path={mdiAccountMultiple} size={32} className="text-emerald-500 mx-auto mb-2" />
                    <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Review Users</span>
                  </Link>
                  <Link href="/verification_submissions/verification_submissions-list" className="p-4 rounded-2xl bg-amber-50 dark:bg-amber-900/20 border border-amber-100 dark:border-amber-800 hover:shadow-lg transition-all text-center">
                    <BaseIcon path={mdiShieldCheck} size={32} className="text-amber-500 mx-auto mb-2" />
                    <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Verifications</span>
                  </Link>
                </>
              )}
              <Link href="/disputes/disputes-list" className="p-4 rounded-2xl bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-800 hover:shadow-lg transition-all text-center">
                <BaseIcon path={mdiAlertCircle} size={32} className="text-red-500 mx-auto mb-2" />
                <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Open Disputes</span>
              </Link>
              <Link href="/messages/messages-list" className="p-4 rounded-2xl bg-purple-50 dark:bg-purple-900/20 border border-purple-100 dark:border-purple-800 hover:shadow-lg transition-all text-center">
                <BaseIcon path={mdiCalendarRange} size={32} className="text-purple-500 mx-auto mb-2" />
                <span className="font-bold text-sm text-slate-700 dark:text-slate-300">Inbox</span>
              </Link>
            </div>
          </CardBox>

          {/* Recent Activity / Status */}
          <CardBox className="h-full">
            <CardBoxComponentTitle title={isBusinessOwner ? 'Business Status' : 'System Status'} />
            <div className="space-y-6">
              <div className="flex items-center justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-800 border border-slate-100 dark:border-slate-700">
                <div className="flex items-center gap-4">
                  <div className={`w-10 h-10 rounded-full flex items-center justify-center ${dashboardData?.verificationStatus === 'Approved' ? 'bg-emerald-500' : 'bg-amber-500'}`}>
                    <BaseIcon path={mdiShieldCheck} size={20} className="text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-sm">Verification Status</h4>
                    <p className="text-xs text-slate-500">{dashboardData?.verificationSubtext || 'Complete verification to build trust'}</p>
                  </div>
                </div>
                <span className={`px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full ${dashboardData?.verificationStatus === 'Approved' ? 'bg-emerald-100 text-emerald-600' : 'bg-amber-100 text-amber-600'}`}>
                  {dashboardData?.verificationStatus || 'N/A'}
                </span>
              </div>

              <div className="flex items-center justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-800 border border-slate-100 dark:border-slate-700">
                <div className="flex items-center gap-4">
                  <div className={`w-10 h-10 rounded-full flex items-center justify-center ${dashboardData?.accountStanding === 'Good' ? 'bg-blue-500' : 'bg-red-500'}`}>
                    <BaseIcon path={mdiChartTimelineVariant} size={20} className="text-white" />
                  </div>
                  <div>
                    <h4 className="font-bold text-sm">Account Standing</h4>
                    <p className="text-xs text-slate-500">{dashboardData?.accountStandingSubtext || 'Perfect track record'}</p>
                  </div>
                </div>
                <span className={`px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full ${dashboardData?.accountStanding === 'Good' ? 'bg-blue-100 text-blue-600' : 'bg-red-100 text-red-600'}`}>
                  {dashboardData?.accountStanding || 'N/A'}
                </span>
              </div>
            </div>
          </CardBox>
        </div>

        {/* Informational Widget */}
        <CardBox className="mt-6 bg-slate-900 text-white border-none overflow-hidden relative">
          <div className="absolute top-0 right-0 w-64 h-64 bg-emerald-500/20 rounded-full -mr-32 -mt-32 blur-3xl"></div>
          <div className="relative z-10 p-4">
            <CardBoxComponentTitle 
              title={isBusinessOwner ? 'Fix-It-Local' : 'Network System Pulse'} 
              className="text-white border-white/10"
            />
            <p className="text-slate-400 text-sm leading-relaxed max-w-2xl mb-6">
              {isBusinessOwner 
                ? 'Welcome to your professional control center. From here you can manage your listings, respond to new leads, and track your business growth across our verified network.'
                : 'The network is operating at optimal capacity. All verification systems are online and AI matching is currently processing requests with 98% efficiency.'}
            </p>
            <div className="flex gap-4">
              <Link href="/docs" className="text-xs font-bold text-emerald-400 hover:text-emerald-300 underline underline-offset-4">
                View Documentation
              </Link>
              <Link href="/support" className="text-xs font-bold text-slate-400 hover:text-white underline underline-offset-4">
                Contact Support
              </Link>
            </div>
          </div>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default Dashboard