import { mdiChartTimelineVariant, mdiPlus, mdiEye, mdiPencil, mdiShieldCheck, mdiCheckDecagram } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'
import TableBusinesses from '../../components/Businesses/TableBusinesses'
import BaseButton from '../../components/BaseButton'
import axios from "axios";
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
import {fetch} from '../../stores/businesses/businessesSlice';
import { useRouter } from 'next/router';
import IconRounded from '../../components/IconRounded';
import BaseButtons from '../../components/BaseButtons';
import BaseIcon from '../../components/BaseIcon';

const BusinessesTablesPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const { businesses, count, loading } = useAppSelector((state) => state.businesses);
  const router = useRouter();
  const dispatch = useAppDispatch();

  useEffect(() => {
    dispatch(fetch({ limit: 50, page: 0 }));
  }, [dispatch]);

  const isVBO = currentUser?.app_role?.name === 'Verified Business Owner';

  // Completion calculation helper
  const calculateCompletion = (business) => {
    const fields = ['name', 'description', 'phone', 'email', 'website', 'address', 'city', 'state', 'zip'];
    let filled = 0;
    fields.forEach(f => {
      if (business[f] && business[f] !== '') filled++;
    });
    return Math.round((filled / fields.length) * 100);
  };

  if (loading) {
    return (
      <SectionMain>
        <div className="flex justify-center items-center h-64">
           <p>Loading your portal...</p>
        </div>
      </SectionMain>
    );
  }

  // State A: No listing exists
  if (isVBO && count === 0) {
    return (
      <>
        <Head>
          <title>{getPageTitle('My Listing')}</title>
        </Head>
        <SectionMain>
          <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="My Listing" main>
            {''}
          </SectionTitleLineWithButton>
          
          <div className="flex flex-col items-center justify-center mt-12">
            <CardBox className="max-w-2xl w-full text-center py-12">
              <IconRounded icon={mdiPlus} color="info" className="mb-6 mx-auto" />
              <h1 className="text-3xl font-bold mb-4">Create your business listing</h1>
              <p className="text-gray-500 mb-8 px-6 text-lg">
                This is what customers see in search results. A complete profile helps you get more leads and builds trust with potential clients.
              </p>
              <BaseButton 
                color="info" 
                label="Create Listing" 
                icon={mdiPlus}
                onClick={() => router.push('/businesses/businesses-new')}
                className="px-8 py-3 text-lg"
              />
            </CardBox>
          </div>
        </SectionMain>
      </>
    );
  }

  // State B: Exactly 1 listing exists
  if (isVBO && count === 1) {
    const business = businesses[0];
    const completion = calculateCompletion(business);

    return (
      <>
        <Head>
          <title>{getPageTitle('My Listing')}</title>
        </Head>
        <SectionMain>
          <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Listing Profile" main>
            <BaseButtons>
                <BaseButton 
                    color="info" 
                    label="Preview Public Profile" 
                    icon={mdiEye} 
                    outline
                    onClick={() => window.open(`/public/businesses-details/?id=${business.id}`, '_blank')}
                />
                <BaseButton 
                    color="warning" 
                    label="Edit" 
                    icon={mdiPencil} 
                    onClick={() => router.push(`/businesses/${business.id}`)}
                />
            </BaseButtons>
          </SectionTitleLineWithButton>

          <CardBox className="mb-6">
            <div className="flex flex-col md:flex-row md:items-center justify-between">
                <div>
                    <h2 className="text-2xl font-bold mb-1">{business.name}</h2>
                    <div className="flex items-center space-x-2">
                        <span className={`px-2 py-1 rounded text-xs font-bold ${business.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}`}>
                            {business.is_active ? 'Active' : 'Inactive'}
                        </span>
                        {business.is_claimed && (
                             <span className="flex items-center text-blue-600 text-xs font-bold">
                                <BaseIcon path={mdiCheckDecagram} size={16} className="mr-1" />
                                Verified
                             </span>
                        )}
                    </div>
                </div>
                {!business.is_claimed && (
                    <BaseButton 
                        color="success" 
                        label="Request Verification" 
                        icon={mdiShieldCheck}
                        className="mt-4 md:mt-0"
                        onClick={() => router.push('/verification_submissions/verification_submissions-new')}
                    />
                )}
            </div>

            <div className="mt-8">
                <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-gray-700 font-bold">Profile completeness</span>
                    <span className="text-sm font-bold text-info">{completion}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-4">
                    <div 
                        className="bg-info h-4 rounded-full transition-all duration-500" 
                        style={{ width: `${completion}%` }}
                    ></div>
                </div>
                <p className="text-xs text-gray-500 mt-2 italic">
                    {completion < 100 ? 'Fill in all details to reach 100% and get better visibility!' : 'Your profile is looking great!'}
                </p>
            </div>
          </CardBox>

          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2 mb-6">
            <CardBox title="Business Details" className="h-full">
                <div className="space-y-4">
                    <div>
                        <p className="text-xs text-gray-400 uppercase font-bold">Phone</p>
                        <p className="font-medium">{business.phone || 'Not provided'}</p>
                    </div>
                    <div>
                        <p className="text-xs text-gray-400 uppercase font-bold">Email</p>
                        <p className="font-medium">{business.email || 'Not provided'}</p>
                    </div>
                    <div>
                        <p className="text-xs text-gray-400 uppercase font-bold">Website</p>
                        <p className="font-medium">{business.website || 'Not provided'}</p>
                    </div>
                    <div>
                        <p className="text-xs text-gray-400 uppercase font-bold">Location</p>
                        <p className="font-medium">
                            {business.city ? `${business.city}, ${business.state}` : 'Not provided'}
                        </p>
                    </div>
                </div>
            </CardBox>

            <CardBox title="About" className="h-full">
                <div className="prose prose-sm max-w-none dark:prose-invert">
                    <div dangerouslySetInnerHTML={{ __html: business.description || '<p class="text-gray-400 italic">No description provided yet.</p>' }} />
                </div>
            </CardBox>
          </div>
          
          <BaseButtons className="mt-6">
             <BaseButton label="Add another location" icon={mdiPlus} color="info" onClick={() => router.push('/businesses/businesses-new')} />
          </BaseButtons>
        </SectionMain>
      </>
    );
  }

  // State C: Multiple listings exist (or Admin view)
  return (
    <>
      <Head>
        <title>{getPageTitle('Businesses')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={isVBO ? "My Locations" : "Service Listings"} main>
             <BaseButton 
                color="info" 
                label={isVBO ? "Add another location" : "New Item"} 
                icon={mdiPlus}
                onClick={() => router.push('/businesses/businesses-new')}
             />
        </SectionTitleLineWithButton>
        
        {isVBO ? (
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
                {businesses.map((business) => {
                    const completion = calculateCompletion(business);
                    return (
                        <CardBox key={business.id} className="hover:shadow-lg transition-shadow">
                            <div className="flex justify-between items-start mb-4">
                                <h3 className="text-xl font-bold truncate pr-2">{business.name}</h3>
                                <span className={`px-2 py-1 rounded text-xs font-bold ${business.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}`}>
                                    {business.is_active ? 'Active' : 'Inactive'}
                                </span>
                            </div>
                            
                            <p className="text-sm text-gray-500 mb-4 h-10 overflow-hidden line-clamp-2">
                                {business.city ? `${business.city}, ${business.state}` : 'Location not set'}
                            </p>
                            
                            <div className="mb-4">
                                <div className="flex justify-between items-center mb-1">
                                    <span className="text-xs font-bold">Completion</span>
                                    <span className="text-xs font-bold">{completion}%</span>
                                </div>
                                <div className="w-full bg-gray-200 rounded-full h-2">
                                    <div 
                                        className="bg-info h-2 rounded-full" 
                                        style={{ width: `${completion}%` }}
                                    ></div>
                                </div>
                            </div>

                            <BaseButtons>
                                <BaseButton 
                                    small 
                                    color="info" 
                                    label="Edit" 
                                    icon={mdiPencil} 
                                    onClick={() => router.push(`/businesses/${business.id}`)} 
                                />
                                <BaseButton 
                                    small 
                                    color="info" 
                                    outline 
                                    label="Preview" 
                                    icon={mdiEye} 
                                    onClick={() => window.open(`/public/businesses-details/?id=${business.id}`, '_blank')}
                                />
                                <BaseButton 
                                    small 
                                    color="info" 
                                    outline 
                                    label="Leads" 
                                    onClick={() => router.push('/leads/leads-list')} 
                                />
                            </BaseButtons>
                        </CardBox>
                    );
                })}
            </div>
        ) : (
            <CardBox className="mb-6" hasTable>
                <TableBusinesses
                    filterItems={[]}
                    setFilterItems={() => { /* nothing to do */ }}
                    filters={[]}
                    showGrid={false}
                />
            </CardBox>
        )}
      </SectionMain>
    </>
  )
}

BusinessesTablesPage.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated
        permission={'READ_BUSINESSES'}
      >
          {page}
      </LayoutAuthenticated>
  )
}

export default BusinessesTablesPage