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,
  mdiCamera,
  mdiDelete,
  mdiUpload
} 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';
import { Form, Formik, Field } from 'formik';
import FormField from '../components/FormField';
import FormImagePicker from '../components/FormImagePicker';

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);
  const [isUploading, setIsUploading] = useState(false);

  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) {
              const resById = await axios.get(`/businesses/${res.data.rows[0].id}`);
              business = resById.data;
          }
      }
      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);
    }
  };

  const handlePhotoUpload = async (values: any, { resetForm }: any) => {
    if (!myBusiness) return;
    setIsUploading(true);
    try {
      // Check if we already have a business_photos record
      const existingPhotosRecord = myBusiness.business_photos_business && myBusiness.business_photos_business[0];
      
      if (existingPhotosRecord) {
        // Update existing record with NEW photos (append)
        await axios.put(`/business_photos/${existingPhotosRecord.id}`, {
          id: existingPhotosRecord.id,
          data: {
            photos: [...(existingPhotosRecord.photos || []), ...values.photos]
          }
        });
      } else {
        // Create new record
        await axios.post('/business_photos', {
          data: {
            business: myBusiness.id,
            photos: values.photos
          }
        });
      }
      // Refresh data
      await fetchData();
      resetForm();
    } catch (error) {
      console.error('Error uploading photos:', error);
    } finally {
      setIsUploading(false);
    }
  };

  const removePhoto = async (photoId: string, businessPhotosRecordId: string) => {
    if (!window.confirm('Are you sure you want to remove this photo?')) return;
    
    try {
      const record = myBusiness.business_photos_business.find((r: any) => r.id === businessPhotosRecordId);
      if (!record) return;
      
      const newPhotos = record.photos.filter((p: any) => p.id !== photoId);
      
      await axios.put(`/business_photos/${businessPhotosRecordId}`, {
        id: businessPhotosRecordId,
        data: {
          photos: newPhotos
        }
      });
      await fetchData();
    } catch (error) {
      console.error('Error removing photo:', error);
    }
  };

  const formatImageUrl = (url: string) => {
    if (!url) return null;
    if (url.startsWith('http') || url.startsWith('/')) {
      return url;
    }
    return `${axios.defaults.baseURL}/file/download?privateUrl=${url}`;
  };

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

  // STATE 1: Owns a business
  if (myBusiness) {
    const allPhotos = myBusiness.business_photos_business?.flatMap((bp: any) => 
      bp.photos?.map((p: any) => ({ ...p, bpId: bp.id }))
    ) || [];

    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 overflow-hidden flex items-center justify-center text-slate-400">
               {allPhotos.length > 0 ? (
                 <img 
                   src={formatImageUrl(allPhotos[0].publicUrl)!} 
                   className="w-full h-full object-cover" 
                   alt="Business"
                 />
               ) : (
                 <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>
        
        {/* Performance & Gallery Section */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
           {/* Stats */}
           <div className="lg:col-span-1 space-y-6">
              <CardBox className="p-6 text-center">
                 <div className="text-slate-400 text-[10px] font-black 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-[10px] font-black uppercase tracking-widest mb-2">Avg Rating</div>
                 <div className="text-3xl font-bold">{myBusiness.rating ? Number(myBusiness.rating).toFixed(1) : 'New'}</div>
              </CardBox>
              <CardBox className="p-10 bg-slate-900 text-white flex flex-col items-center justify-center text-center rounded-[2.5rem]">
                 <div className="w-12 h-12 bg-emerald-500 rounded-2xl flex items-center justify-center mb-4">
                    <BaseIcon path={mdiShieldCheck} size={24} />
                 </div>
                 <h4 className="font-bold mb-1">Reliability Score</h4>
                 <div className="text-4xl font-black text-emerald-400">{myBusiness.reliability_score || 0}%</div>
              </CardBox>
           </div>

           {/* Gallery Management */}
           <CardBox className="lg:col-span-2 p-8 rounded-[3rem]">
              <div className="flex items-center justify-between mb-8">
                 <h3 className="text-2xl font-bold flex items-center">
                    <BaseIcon path={mdiCamera} size={28} className="mr-3 text-emerald-500" />
                    Portfolio Gallery
                 </h3>
                 <span className="text-slate-400 text-sm font-medium">{allPhotos.length} Pictures</span>
              </div>

              {/* Upload Form */}
              <div className="mb-8 p-6 bg-slate-50 rounded-3xl border border-dashed border-slate-200">
                 <Formik
                   initialValues={{ photos: [] }}
                   onSubmit={handlePhotoUpload}
                 >
                   <Form className="flex flex-col md:flex-row items-end gap-4">
                      <div className="flex-grow w-full">
                         <FormField label="Add new pictures to your listing" help="Show clients your best work. High-quality photos increase bookings.">
                            <Field
                              label='Choose Photos'
                              color='info'
                              icon={mdiUpload}
                              path={'business_photos/photos'}
                              name='photos'
                              id='photos'
                              schema={{
                                size: undefined,
                                formats: undefined,
                              }}
                              component={FormImagePicker}
                            />
                         </FormField>
                      </div>
                      <BaseButton 
                        type="submit" 
                        color="info" 
                        label={isUploading ? "Uploading..." : "Add to Gallery"} 
                        disabled={isUploading}
                        className="mb-4"
                      />
                   </Form>
                 </Formik>
              </div>

              {/* Current Photos Grid */}
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                 {allPhotos.map((photo: any) => (
                   <div key={photo.id} className="group relative aspect-square rounded-2xl overflow-hidden bg-slate-100 border border-slate-200">
                      <img 
                        src={formatImageUrl(photo.publicUrl)!} 
                        alt="Business"
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                      />
                      <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                         <button 
                            onClick={() => removePhoto(photo.id, photo.bpId)}
                            className="bg-white/20 hover:bg-red-500 text-white p-3 rounded-xl backdrop-blur-md transition-all"
                            title="Remove Photo"
                         >
                            <BaseIcon path={mdiDelete} size={20} />
                         </button>
                      </div>
                   </div>
                 ))}
                 {allPhotos.length === 0 && (
                   <div className="col-span-full py-12 text-center text-slate-400 italic">
                      No photos in your gallery yet. Add some to stand out!
                   </div>
                 )}
              </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;