import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { 
  mdiStorefront, 
  mdiShieldCheck, 
  mdiAlertCircle, 
  mdiCheckCircle,
  mdiPlus,
  mdiMagnify,
  mdiPencil
} from '@mdi/js';
import axios from 'axios';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import CardBox from '../components/CardBox';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import LoadingSpinner from '../components/LoadingSpinner';
import { useAppSelector } from '../stores/hooks';
import { getPageTitle } from '../config';

const MyListingPage = () => {
  const router = useRouter();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [loading, setLoading] = useState(true);
  const [myBusiness, setMyBusiness] = useState<any>(null);
  const [pendingClaim, setPendingClaim] = useState<any>(null);

  useEffect(() => {
    if (currentUser) {
      fetchData();
    }
  }, [currentUser]);

  const fetchData = async () => {
    setLoading(true);
    try {
      // 1. Fetch owned business
      let business = null;
      if (currentUser.businessId) {
          const res = await axios.get(`/businesses/${currentUser.businessId}`);
          business = res.data;
      } else {
          // Search by owner_userId if businessId is not set on user record yet
          const res = await axios.get('/businesses', { params: { owner_userId: currentUser.id } });
          if (res.data.rows && res.data.rows.length > 0) {
              business = res.data.rows[0];
          }
      }
      setMyBusiness(business);

      // 2. If no business, fetch pending claim
      if (!business) {
          const res = await axios.get('/claim_requests', { params: { userId: currentUser.id, status: 'PENDING' } });
          if (res.data.rows && res.data.rows.length > 0) {
              setPendingClaim(res.data.rows[0]);
          }
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <SectionMain><LoadingSpinner /></SectionMain>;

  // STATE 1: Owns a business
  if (myBusiness) {
    return (
      <SectionMain>
        <Head>
          <title>{getPageTitle('My Listing')}</title>
        </Head>
        <SectionTitleLineWithButton icon={mdiStorefront} title="My Listing" main>
          <BaseButton 
            href={`/businesses/businesses-edit/?id=${myBusiness.id}`} 
            icon={mdiPencil} 
            label="Edit Listing" 
            color="info" 
          />
        </SectionTitleLineWithButton>

        <CardBox className="mb-6">
          <div className="flex flex-col md:flex-row items-center gap-8 p-4">
            <div className="w-32 h-32 bg-slate-100 rounded-3xl flex items-center justify-center text-slate-400">
               <BaseIcon path={mdiStorefront} size={48} />
            </div>
            <div className="flex-grow text-center md:text-left">
              <h2 className="text-3xl font-bold mb-2">{myBusiness.name}</h2>
              <p className="text-slate-500 mb-4">{myBusiness.address}, {myBusiness.city}, {myBusiness.state}</p>
              <div className="flex flex-wrap justify-center md:justify-start gap-4">
                <span className="bg-emerald-50 text-emerald-600 px-3 py-1 rounded-full text-xs font-bold uppercase">Active Listing</span>
                <span className="bg-blue-50 text-blue-600 px-3 py-1 rounded-full text-xs font-bold uppercase">Verified Owner</span>
              </div>
            </div>
            <div className="flex flex-col gap-2">
               <BaseButton 
                  href={`/public/businesses-details?id=${myBusiness.id}`} 
                  label="View Public Profile" 
                  outline 
                  color="info"
                />
            </div>
          </div>
        </CardBox>
        
        {/* Placeholder for stats or recent bookings */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
           <CardBox className="p-6 text-center">
              <div className="text-slate-400 text-xs font-bold uppercase tracking-widest mb-2">Total Love Letters</div>
              <div className="text-3xl font-bold">{myBusiness.reviews_business?.length || 0}</div>
           </CardBox>
           <CardBox className="p-6 text-center">
              <div className="text-slate-400 text-xs font-bold uppercase tracking-widest mb-2">Avg Rating</div>
              <div className="text-3xl font-bold">{myBusiness.rating || 'New'}</div>
           </CardBox>
           <CardBox className="p-6 text-center">
              <div className="text-slate-400 text-xs font-bold uppercase tracking-widest mb-2">Service Bookings</div>
              <div className="text-3xl font-bold">0</div>
           </CardBox>
        </div>
      </SectionMain>
    );
  }

  // STATE 2: Pending claim
  if (pendingClaim) {
    return (
      <SectionMain>
        <Head>
          <title>{getPageTitle('Claim Pending')}</title>
        </Head>
        <SectionTitleLineWithButton icon={mdiShieldCheck} title="Claim Verification" main />

        <div className="max-w-3xl mx-auto">
          <CardBox className="p-10 text-center space-y-6">
            <div className="w-20 h-20 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto">
              <BaseIcon path={mdiAlertCircle} size={48} />
            </div>
            <div>
              <h2 className="text-3xl font-bold mb-2">Claim Request Pending</h2>
              <p className="text-slate-500 max-w-md mx-auto">
                We&apos;ve received your request to claim <strong>{pendingClaim.business?.name}</strong>. 
                Our team is currently reviewing your application.
              </p>
            </div>

            <div className="bg-slate-50 p-6 rounded-2xl border border-slate-200 inline-block text-left w-full max-w-md">
              <h4 className="font-bold mb-4 flex items-center">
                <BaseIcon path={mdiShieldCheck} size={20} className="mr-2 text-emerald-500" />
                Next Steps: Verification
              </h4>
              <p className="text-sm text-slate-600 mb-6">
                To approve your claim, we need to verify your association with this business. Please upload a business license or utility bill.
              </p>
              <BaseButton 
                href={`/verification_submissions/verification_submissions-new?businessId=${pendingClaim.businessId}`}
                label="Upload Verification Documents" 
                color="info"
                className="w-full"
              />
            </div>

            <div className="pt-6 border-t border-slate-100">
               <p className="text-xs text-slate-400">Request ID: {pendingClaim.id} • Submitted on {new Date(pendingClaim.createdAt).toLocaleDateString()}</p>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    );
  }

  // STATE 3: Neither
  return (
    <SectionMain>
      <Head>
        <title>{getPageTitle('My Listing')}</title>
      </Head>
      <SectionTitleLineWithButton icon={mdiStorefront} title="My Listing" main />

      <div className="grid md:grid-cols-2 gap-8 max-w-5xl mx-auto pt-10">
        
        {/* Path 1: Create New */}
        <CardBox className="p-10 flex flex-col items-center text-center space-y-6 hover:shadow-xl transition-all border-2 border-transparent hover:border-emerald-100">
          <div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-2xl flex items-center justify-center">
            <BaseIcon path={mdiPlus} size={40} />
          </div>
          <div>
            <h3 className="text-2xl font-bold mb-2">Create New Listing</h3>
            <p className="text-slate-500 text-sm">
              Your business isn&apos;t on Fix-It-Local yet? Create a fresh listing and start attracting clients immediately.
            </p>
          </div>
          <BaseButton 
            href="/businesses/businesses-new" 
            label="Start Fresh Listing" 
            color="info" 
            className="w-full"
          />
        </CardBox>

        {/* Path 2: Claim Existing */}
        <CardBox className="p-10 flex flex-col items-center text-center space-y-6 hover:shadow-xl transition-all border-2 border-transparent hover:border-blue-100">
          <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-2xl flex items-center justify-center">
            <BaseIcon path={mdiMagnify} size={40} />
          </div>
          <div>
            <h3 className="text-2xl font-bold mb-2">Claim Existing Business</h3>
            <p className="text-slate-500 text-sm">
              Search for your business in our directory. If it exists but is unowned, you can claim it for free.
            </p>
          </div>
          <BaseButton 
            href="/search" 
            label="Search Directory" 
            outline 
            color="info" 
            className="w-full"
          />
        </CardBox>

      </div>
    </SectionMain>
  );
};

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

export default MyListingPage;