'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import {
  signUpStart,
  signUpSuccess,
  signUpFailure,
  resetErrorAndMessage,
} from '@/lib/store/slices/userSlice';

import { BusinessProfileForm } from './BusinessProfileForm';
import { InvestorProfileForm } from './InvestorProfileForm';
import { IndividualForm } from './IndividualForm';
import { getAllAccountTypes } from '@/lib/api/client';
import { toast } from 'sonner';
import Link from 'next/link';
import Image from 'next/image';
import { Loader } from 'lucide-react';

interface SignUpFormProps {
  logoImage?: any;
  countries?: any[];
  storeLinks?: any[];
}

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface AccountType {
  id: string;
  label: string;
  value: string;
  displayOrder: number;
}

// ✅ Skeleton Loader Component for Account Types
const AccountTypeSkeleton = () => {
  return (
    <div className="max-w-md mx-auto bg-white/80 backdrop-blur-xl px-5 md:py-2 py-4 rounded-2xl">
      <div className="flex justify-center items-center mb-4">
        <div className="h-6 w-40 bg-gray-200 rounded animate-pulse"></div>
      </div>
      
      {/* Radio Buttons Skeleton */}
      <div className="flex justify-center gap-6 mt-3 mb-4 flex-wrap">
        <div className="h-5 w-16 bg-gray-200 rounded animate-pulse"></div>
        <div className="h-5 w-16 bg-gray-200 rounded animate-pulse"></div>
        <div className="h-5 w-16 bg-gray-200 rounded animate-pulse"></div>
      </div>
      
      {/* Form Skeleton */}
      <div className="space-y-3 animate-pulse">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
          <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
          <div><div className="h-2 w-14 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
          <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
        </div>
        <div className="h-9 w-full bg-gray-200 rounded-lg mt-2"></div>
      </div>
      
      {/* Store Links Skeleton */}
      <div className="flex gap-2.5 justify-center mt-4">
        <div className="h-8 w-24 bg-gray-200 rounded animate-pulse"></div>
        <div className="h-8 w-24 bg-gray-200 rounded animate-pulse"></div>
      </div>
    </div>
  );
};

export function SignUpForm({ logoImage, countries = [], storeLinks = [] }: SignUpFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const searchParams = useSearchParams();
  const { loading } = useAppSelector((state) => state.user);

  const [accountTypes, setAccountTypes] = useState<AccountType[]>([]);
  const [isLoadingTypes, setIsLoadingTypes] = useState(true);
  const [accountType, setAccountType] = useState<string>('');

  // Fetch account types from API
  useEffect(() => {
    const fetchAccountTypes = async () => {
      try {
        const result = await getAllAccountTypes(logoImage?.securityKey);
        if (result.success && result.data && result.data.length > 0) {
          setAccountTypes(result.data);
          // Set default from URL param or first account type
          const urlType = searchParams.get('type');
          const defaultType = result.data.find((t: AccountType) => t.id === urlType)?.id || result.data[0]?.id;
          setAccountType(defaultType);
        } else {
          toast.error('Failed to load account types');
        }
        setIsLoadingTypes(false);
      } catch (error) {
        console.error('Failed to fetch account types:', error);
        toast.error('Failed to load account types');
        setIsLoadingTypes(false);
      }
    };

    fetchAccountTypes();
  }, [logoImage?.securityKey, searchParams]);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  const handleSuccess = (userData: any) => {
    dispatch(signUpSuccess(userData));
    router.push('/verify-otp');
  };

  // Sort account types by displayOrder
  const sortedAccountTypes = [...accountTypes].sort((a, b) => a.displayOrder - b.displayOrder);

  // ✅ Show Skeleton while loading account types
  if (isLoadingTypes) {
    return <AccountTypeSkeleton />;
  }

  if (accountTypes.length === 0) {
    return (
      <div className="max-w-md mx-auto bg-white/80 backdrop-blur-xl px-5 md:py-2 py-4 rounded-2xl">
        <div className="text-center py-8 text-red-500">
          Failed to load account types. Please refresh the page.
        </div>
      </div>
    );
  }

  return (
    <div className="w-full mx-auto bg-white/80 backdrop-blur-xl px-5 md:py-2 py-4 rounded-2xl">
      <span className="text-[20px] text-center text-[#1E222A] block">
        Create Your Account
      </span>

      {/* ✅ Dynamic Radio Buttons */}
      <div className="flex justify-center gap-6 mt-1 mb-3 flex-wrap">
        {sortedAccountTypes.map((tab) => (
          <label key={tab.id} className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name="accountType"
              value={tab.id}
              checked={accountType === tab.id}
              onChange={() => setAccountType(tab.id)}
className="w-4 h-4 accent-[#0084a5] bg-transparent border-gray-400"
            />
            <span className="text-sm text-gray-700">{tab.label}</span>
          </label>
        ))}
      </div>

      {/* Conditional Form Rendering based on value */}
      {accountType === 'innovator' && (
        <IndividualForm
          logoImage={logoImage}
          countries={countries}
          onSuccess={handleSuccess}
          loading={loading}
        />
      )}
      
      {accountType === 'business' && (
        <BusinessProfileForm
          logoImage={logoImage}
          countries={countries}
          onSuccess={handleSuccess}
          loading={loading}
        />
      )}
      
      {accountType === 'investor' && (
        <InvestorProfileForm
          logoImage={logoImage}
          countries={countries}
          onSuccess={handleSuccess}
          loading={loading}
        />
      )}

      {/* App Store Links */}
      <div className="flex gap-2.5 justify-center mt-4">
        {storeLinks?.map((store: any) => (
          <Link
            href={store?.socialLink}
            target="_blank"
            key={store?._id}
            className="cursor-pointer transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
          >
            <Image
              width={100}
              height={25}
              src={`${BASE_URL}/${store?.socialIcon}`}
              alt={store?.socialTitle || "Store"}
              className="rounded-md"
            />
          </Link>
        ))}
      </div>
    </div>
  );
}