/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState, useEffect } from 'react';
import { Copy, Check } from 'lucide-react';
import { PageHeader } from '../../components/PageHeader';
import Button from '../../components/Button';
import {fetchReferralData, setAuthToken} from '../../lib/api/api'
import { useAuth } from '../../context/AuthContext';
import Loader from '../../components/loader';

interface ReferralStepProps {
  icon?: React.ReactNode;
  title: string;
  description: string;
  isConnected?: boolean;
  direction?: "left" | "right";
}

const ReferralStep: React.FC<ReferralStepProps> = ({
  icon,
  title,
  description,
  isConnected = true,
  direction = "right",
}) => {
  return (
    <div className="flex flex-col items-center text-center relative p-4">
      {/* Circle Icon */}
      <div className="w-28 h-28 rounded-full bg-gray-100 flex items-center justify-center mb-6 relative z-10">
        {icon || <div className="w-14 h-14 rounded-full bg-gray-200" />}
      </div>

      {/* Title */}
      <h3 className="text-base font-semibold text-gray-900 mb-2">{title}</h3>

      {/* Description */}
      <p className="text-gray-600 text-sm max-w-xs px-12">{description}</p>

      {/* Centered Curved Dashed Line */}
      {isConnected && (
        <div
          className={`absolute top-8 hidden lg:block ${
            direction === "right"
              ? "left-1/2 translate-x-[110px]"
              : "right-1/2 -translate-x-20 rotate-180"
          }`}
        >
          <svg
            width="180"
            height="80"
            viewBox="0 0 180 80"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            className="animate-dash"
          >
            <path
              d="M0,40 C60,0 120,0 180,40"
              stroke="#1C1C1C99"
              strokeWidth="2"
              strokeDasharray="6,6"
              fill="transparent"
            />
          </svg>
        </div>
      )}
    </div>
  );
};

// Referral Steps Container
interface ReferralStepsProps {
  steps: {
    icon?: React.ReactNode;
    title: string;
    description: string;
  }[];
}

const ReferralSteps: React.FC<ReferralStepsProps> = ({ steps }) => {
  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-16 relative">
      {steps.map((step, index) => (
        <ReferralStep
          key={index}
          {...step}
          isConnected={index < steps.length - 1}
        />
      ))}
    </div>
  );
};

// Invite Section Component
interface InviteSectionProps {
  title: string;
  description: string;
  placeholder: string;
  onSubmit: (email: string) => void;
}

const InviteSection: React.FC<InviteSectionProps> = ({
  title,
  description,
  placeholder,
  onSubmit,
}) => {
  const [email, setEmail] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(email);
    setEmail('');
  };

  return (
    <div className="mb-12">
      <h3 className="text-2xl font-bold text-gray-900 mb-2">{title}</h3>
      <p className="text-gray-600 mb-6">{description}</p>

      <div className='flex gap-12'>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={placeholder}
          className="w-full px-6 py-4 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500 transition"
        />
        
        <Button
          type='button'
          width='30%'
          onClick={() => handleSubmit({ preventDefault: () => {} } as React.FormEvent)}
        >
          Send Invitation
        </Button>
      </div>
    </div>
  );
};

// Referral Link Component
interface ReferralLinkProps {
  title: string;
  description: string;
  referralCode: string;
}

const ReferralLink: React.FC<ReferralLinkProps> = ({
  title,
  description,
  referralCode,
}) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(referralCode);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div>
      <h3 className="text-2xl font-bold text-gray-900 mb-2">{title}</h3>
      <p className="text-gray-600 mb-6">{description}</p>

      <div className="flex items-center gap-4 bg-gray-50 rounded-full px-6 py-4 border border-gray-200">
        <span className="flex-1 text-gray-700 font-mono text-sm truncate">
          {referralCode}
        </span>
        <button
          onClick={handleCopy}
          className="p-2 hover:bg-gray-200 rounded-lg transition"
          title="Copy referral link"
        >
          {copied ? (
            <Check size={20} className="text-green-600" />
          ) : (
            <Copy size={20} className="text-gray-600" />
          )}
        </button>
      </div>
    </div>
  );
};


export default function ReferralsPage() {
  const { token } = useAuth();
  setAuthToken(token);
  const [loading, setLoading] = useState(true);
  const [referralDetails, setReferralDetails] = useState<any>(null);
//   const [inviteEmail, setInviteEmail] = useState('');

  // Fetch referral data once in the parent component
  useEffect(() => {
    if (!token) return;
  
    let isMounted = true;
    setLoading(true);
  
    const fetchData = async () => {
      try {
        const res = await fetchReferralData();
        if (isMounted) {
          console.log(res.data.data);
          setReferralDetails(res.data.data);
        }
      } catch (error) {
        console.error("Error fetching referral data:", error);
      } finally {
        if (isMounted) setLoading(false);
      }
    };
  
    fetchData();
  
    return () => {
      isMounted = false;
    };
  }, [token]);

  const referralSteps = [
    {
      title: 'Share your code',
      description: 'Send your referral link to your friends and then tell them how cool SUBA is',
    },
    {
      title: 'Friends sign up',
      description: 'Your friend signs up using your code, completes KYC, funds wallet, and create investment plan',
    },
    {
      title: 'Earn your reward',
      description: 'Once all steps are completed, you receive N500 in your SUBA wallet',
    },
  ];

  const handleInviteSubmit = (email: string) => {
    console.log('Inviting:', email);
    // Add your invite logic here
  };

  // Use referral code from API if available
  const referralCode = referralDetails?.referralCode || 'type=canvas&t=Xvnosx3EYI5EF6BT-O';

  if (loading) {
    return (
      <main className="flex justify-center items-center h-screen bg-white">
        <Loader />
      </main>
    );
  }

  return (
    <div className="min-h-screen bg-white p-4 sm:p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <PageHeader
          title="Referrals"
          description="This is an overview of your savings and investment activities"
        />

        {/* Referral Steps */}
        <ReferralSteps steps={referralSteps} />

        {/* Invite Section */}
        <InviteSection
          title="Invite your friends"
          description="Tell your friends how cool SUBA Capital is and start earning now"
          placeholder="Email address"
          onSubmit={handleInviteSubmit}
        />

        {/* Referral Link */}
        <ReferralLink
          title="Share the referral link"
          description="Spread the word! I am hitting my financial goals with SUBA Capital"
          referralCode={referralCode}
        />
      </div>
    </div>
  );
}