// components/invite/InviteFriends.tsx
'use client';

import React, { useState, useEffect } from "react";
import Image from "next/image";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { 
  inviteFriendsFailure, 
  inviteFriendsStart, 
  inviteFriendsSuccess, 
  resetErrorAndMessage 
} from "@/lib/store/slices/userSlice";
import { 
  Loader, 
  Plus, 
  X, 
  Clock, 
  CheckCircle, 
  AlertCircle,
  RefreshCw,
  Users,
  Mail,
  UserPlus
} from "lucide-react";
import { inviteFriends, getInviteHistory, resendInvite } from "@/lib/api/client";
import { formatDistanceToNow, format } from "date-fns";
import { RootState } from "@/lib/store/store";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface InviteFriend {
  _id?: string;
  email: string;
  createdAt: string;
  expiresAt?: string;
  accountCreated: boolean;
  isExpired?: boolean;
}

interface InviteHistoryData {
  invitedFriends: InviteFriend[];
  totalInvites: number;
  acceptedInvites: number;
  pendingInvites: number;
  expiredInvites: number;
}

interface InviteFriendsData {
  mainImage?: string;
  pageTitle?: string;
  description?: string;
}

interface LogoImage {
  securityKey?: string;
  [key: string]: any;
}

interface InviteFriendsProps {
  inviteFriendsData: InviteFriendsData;
  logoImage: LogoImage;
}

const InviteFriends = ({ inviteFriendsData, logoImage }: InviteFriendsProps) => {
  const dispatch = useDispatch();
  const router = useRouter();
const { currentCustomer, accessToken, loading: authLoading } = useSelector((state: RootState) => state.user);
  
  const [emailArray, setEmailArray] = useState<string[]>([]);
  const [email, setEmail] = useState<string>("");
  const [showEmailArray, setShowEmailArray] = useState<boolean>(false);
  const [inviteHistory, setInviteHistory] = useState<InviteHistoryData>({
    invitedFriends: [],
    totalInvites: 0,
    acceptedInvites: 0,
    pendingInvites: 0,
    expiredInvites: 0
  });
  const [loadingHistory, setLoadingHistory] = useState<boolean>(false);
  const [resendingEmail, setResendingEmail] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'send' | 'history'>('send');
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);

  useEffect(() => {
    if (accessToken) {
      fetchInviteHistory();
    }
  }, [accessToken]);

const fetchInviteHistory = async () => {
  setLoadingHistory(true);
  try {
    
    const response = await getInviteHistory(accessToken, logoImage?.securityKey);
    
    if (response.success && response.data) {
      
      const expiredCount = response.data.invitedFriends?.filter(
        (friend: InviteFriend) => !friend.accountCreated && friend.isExpired
      ).length || 0;
      
      setInviteHistory({
        ...response.data,
        expiredInvites: expiredCount
      });
    } else {
      console.error("❌ API failed:", response.message);
    }
  } catch (error) {
    console.error("❌ Error fetching invite history:", error);
  } finally {
    setLoadingHistory(false);
  }
};

  const handleResendInvite = async (email: string) => {
    setResendingEmail(email);
    try {
      const response = await resendInvite(
        { email }, 
        accessToken, 
        logoImage?.securityKey
      );
      if (response.success) {
        toast.success("Invite resent successfully!");
        fetchInviteHistory();
      } else {
        toast.error(response.message);
      }
    } catch (error) {
      toast.error("Failed to resend invite");
    } finally {
      setResendingEmail(null);
    }
  };

  const addEmail = () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email) {
      toast.error("Please enter an email address");
      return;
    }
    if (!emailRegex.test(email)) {
      toast.error("Please enter a valid email address");
      return;
    }
    if (emailArray.includes(email)) {
      toast.warning("This email is already added");
      return;
    }
    setEmailArray([...emailArray, email]);
    setShowEmailArray(true);
    setEmail("");
  };
  
  const removeEmail = (index: number) => {
    const updated = emailArray.filter((_, i) => i !== index);
    setEmailArray(updated);
    if (updated.length === 0) setShowEmailArray(false);
  };

  const editEmail = (index: number, newValue: string) => {
    const updated = [...emailArray];
    updated[index] = newValue;
    setEmailArray(updated);
  };
    
  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();
    if (emailArray.length === 0) {
      toast.error("Please add at least one email");
      return;
    }
    
    const uniqueEmails = [...new Set(emailArray.map(e => e.toLowerCase()))];
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const invalidEmails = uniqueEmails.filter(e => !emailRegex.test(e));
    
    if (invalidEmails.length > 0) {
      toast.error(`Invalid email(s): ${invalidEmails.join(", ")}`);
      return;
    }
    
    setIsSubmitting(true);
    // dispatch(inviteFriendsStart());
    
    try {
      const result = await inviteFriends(accessToken, uniqueEmails, logoImage?.securityKey);
      if (result.success) {
        dispatch(inviteFriendsSuccess({ message: result.message }));
        toast.success(result.message);
        setEmailArray([]);
        setShowEmailArray(false);
        setEmail("");
        fetchInviteHistory();
      } else {
        dispatch(inviteFriendsFailure(result.message));
        toast.error(result.message);
      }
    } catch (error) {
      dispatch(inviteFriendsFailure("Failed to send invites"));
      toast.error("Failed to send invites");
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (!currentCustomer && !accessToken && !authLoading) {
      router.push("/");
    }
  }, [currentCustomer, accessToken, authLoading, router]);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  const formatExpiryTime = (expiresAt: string) => {
    if (!expiresAt) return '';
    const expiryDate = new Date(expiresAt);
    const now = new Date();
    if (now > expiryDate) return 'Expired';
    return formatDistanceToNow(expiryDate, { addSuffix: true });
  };

  // Skeleton loader for the invite button
 const InviteButtonLoader = () => (
    <button 
      disabled 
      className="w-32 cursor-pointer px-4 py-2 bg-primary/70 text-primary-foreground rounded-lg font-medium flex items-center justify-center gap-2"
    >
      <Loader className="w-4 h-4 animate-spin" />
      <span>Inviting...</span>
    </button>
  );

  if (authLoading && !currentCustomer) {
    return (
      <div className="flex justify-center py-12">
        <Loader className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!currentCustomer && !accessToken) return null;


  return (
    <div className="w-full">
      <div className="flex flex-col gap-6">
        {/* Header */}
        <div>
          <h1 className="text-2xl font-bold text-foreground">Invite Friends</h1>
          <p className="text-muted-foreground mt-1">Grow the CheckUrIdea community together</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-card rounded-xl border p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 dark:bg-blue-900/20 rounded-lg">
                <Mail className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Total Invites</p>
                <p className="text-2xl font-bold text-foreground">{inviteHistory.totalInvites}</p>
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-green-100 dark:bg-green-900/20 rounded-lg">
                <CheckCircle className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Accepted</p>
                <p className="text-2xl font-bold text-green-600">{inviteHistory.acceptedInvites}</p>
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-yellow-100 dark:bg-yellow-900/20 rounded-lg">
                <Clock className="w-5 h-5 text-yellow-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Pending</p>
                <p className="text-2xl font-bold text-yellow-600">{inviteHistory.pendingInvites}</p>
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl border p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-red-100 dark:bg-red-900/20 rounded-lg">
                <AlertCircle className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Expired</p>
                <p className="text-2xl font-bold text-red-600">{inviteHistory.expiredInvites}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-2 border-b">
          <button
            onClick={() => setActiveTab('send')}
            className={`px-4 py-2 text-sm cursor-pointer font-medium transition-colors ${
              activeTab === 'send'
                ? 'text-primary border-b-2 border-primary'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <UserPlus className="w-4 h-4 inline mr-2" />
            Send New Invites
          </button>
          <button
            onClick={() => setActiveTab('history')}
            className={`px-4 py-2 cursor-pointer text-sm font-medium transition-colors ${
              activeTab === 'history'
                ? 'text-primary border-b-2 border-primary'
                : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <Users className="w-4 h-4 inline mr-2" />
            Invite History ({inviteHistory.totalInvites})
          </button>
        </div>

        {/* Content */}
        {activeTab === 'send' ? (
          <div className="bg-card rounded-xl border p-6">
            <div className="flex items-center justify-center w-full h-40 mb-6">
              {inviteFriendsData?.mainImage ? (
                <Image 
                  src={`${BASE_URL}/${inviteFriendsData.mainImage}`} 
                  alt="invite-friends" 
                  width={250} 
                  height={150} 
                  className="rounded-lg object-contain" 
                  priority 
                />
              ) : (
                <div className="w-full h-full bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 rounded-xl flex items-center justify-center">
                  <Mail className="w-16 h-16 text-blue-300 dark:text-blue-700" />
                </div>
              )}
            </div>
            
            <form onSubmit={submitForm} className="flex flex-col gap-4">
              <p className="text-sm text-muted-foreground">
                “Share innovation. Invite your friends to explore CheckUrIdea and grow together.”
              </p>
              
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium">Friend's Email</label>
                <div className="flex gap-2">
                  <input 
                    onChange={(e) => setEmail(e.target.value)} 
                    value={email} 
                    type="text" 
                    placeholder="e.g., abc123@gmail.com" 
                    className="flex-1 bg-secondary rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                  <button 
                    onClick={addEmail} 
                    type="button" 
                    className="flex items-center cursor-pointer gap-2 px-3 py-2 bg-secondary hover:bg-secondary/80 rounded-lg transition-colors"
                  >
                    <Plus className="w-4 h-4" />
                    <span className="hidden sm:inline text-sm">Add</span>
                  </button>
                </div>
              </div>
              
              {showEmailArray && emailArray.length > 0 && (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {emailArray.map((emailItem, index) => (
                    <div key={index} className="flex items-center gap-2 bg-secondary/50 rounded-lg p-2">
                      <input
                        type="text"
                        onChange={(e) => editEmail(index, e.target.value)}
                        value={emailItem}
                        className="flex-1 bg-transparent text-sm focus:outline-none"
                      />
                      <button
                        onClick={() => removeEmail(index)}
                        className="w-5 h-5 cursor-pointer rounded-full bg-red-500 flex items-center justify-center hover:bg-red-600"
                      >
                        <X className="w-3 h-3 text-white" />
                      </button>
                    </div>
                  ))}
                </div>
              )}

              {isSubmitting ? (
                                <InviteButtonLoader />

              ) : (
                <button 
                  type="submit" 
                  disabled={emailArray.length === 0} 
                  className="w-32 cursor-pointer px-4 py-2 bg-primary hover:bg-primary/90 text-primary-foreground rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Invite
                </button>
              )}
            </form>
          </div>
        ) : (
          <div className="bg-card rounded-xl border p-6">
            <h3 className="text-lg font-semibold mb-4">Your Invites</h3>
            
            {loadingHistory ? (
              <div className="flex justify-center py-12">
                <Loader className="w-8 h-8 animate-spin text-primary" />
              </div>
            ) : inviteHistory.invitedFriends.length === 0 ? (
              <div className="text-center py-12">
                <Users className="w-16 h-16 text-muted-foreground mx-auto mb-3" />
                <p className="text-muted-foreground">No invites sent yet</p>
                <button
                  onClick={() => setActiveTab('send')}
                  className="mt-3 cursor-pointer text-sm text-primary hover:underline"
                >
                  Send your first invite →
                </button>
              </div>
            ) : (
              <div className="space-y-3">
                {inviteHistory.invitedFriends.map((friend, index) => (
                  <div key={index} className="bg-secondary/30 p-4 rounded-lg">
                    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <Mail className="w-4 h-4 text-muted-foreground" />
                          <p className="text-sm font-medium">{friend.email}</p>
                        </div>
                        
                        <div className="flex flex-wrap items-center gap-3">
                          {friend.accountCreated ? (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-700 text-xs rounded-full">
                              <CheckCircle className="w-3 h-3" /> Joined
                            </span>
                          ) : friend.isExpired ? (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-red-100 dark:bg-red-900/30 text-red-700 text-xs rounded-full">
                              <AlertCircle className="w-3 h-3" /> Expired
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 text-xs rounded-full">
                              <Clock className="w-3 h-3" /> Pending
                            </span>
                          )}

                          <span className="text-xs text-muted-foreground">
                            Invited {format(new Date(friend.createdAt), 'dd MMM yyyy')}
                          </span>

                          {!friend.accountCreated && friend.expiresAt && (
                            <span className="text-xs">
                              {friend.isExpired ? (
                                <span className="text-red-500">Expired on {format(new Date(friend.expiresAt), 'dd MMM yyyy')}</span>
                              ) : (
                                <span className="text-primary">Expires {formatExpiryTime(friend.expiresAt)}</span>
                              )}
                            </span>
                          )}
                        </div>
                      </div>

                      {!friend.accountCreated && friend.isExpired && (
                        <button
                          onClick={() => handleResendInvite(friend.email)}
                          disabled={resendingEmail === friend.email}
                          className="px-3 py-1 text-sm cursor-pointer bg-red-50 hover:bg-red-100 dark:bg-red-900/20 text-red-600 rounded-lg flex items-center gap-1 disabled:opacity-50"
                        >
                          {resendingEmail === friend.email ? (
                            <Loader className="w-3 h-3 animate-spin" />
                          ) : (
                            <RefreshCw className="w-3 h-3" />
                          )}
                          Resend
                        </button>
                      )}
                      
                      {!friend.accountCreated && !friend.isExpired && (
                        <span className="text-xs text-muted-foreground flex items-center gap-1">
                          <Clock className="w-3 h-3" /> Waiting
                        </span>
                      )}
                      
                      {friend.accountCreated && (
                        <span className="text-xs text-green-500 flex items-center gap-1">
                          <CheckCircle className="w-3 h-3" /> Registered
                        </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default InviteFriends;