import { motion } from "motion/react";
import { Plus, X, CheckCircle, XCircle, Loader2 } from "lucide-react";
import { useState, useEffect, useMemo } from "react";
import { getCachedProfile } from "../../../../services/profileService";
import { API_BASE_URL } from "../../../../config/api";

export interface Teammate {
  id: string;
  phone: string;
  fullName?: string;
  userId?: string;
  isVerifying?: boolean;
  error?: string;
}

interface TeammatesSectionProps {
  teammates: Teammate[];
  onAdd: () => void;
  onRemove: (id: string) => void;
  onChange: (id: string, value: string) => void;
  onVerify: (id: string, fullName: string, userId: string, error?: string) => void;
}

const inputStyle = {
  backgroundImage:
    "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
  backgroundOrigin: "border-box",
  backgroundClip: "padding-box, border-box",
  border: "1px solid #d680ff66",
  boxShadow:
    "0 -7px 20px rgba(7, 0, 18, 0.46), 0 6px 14px rgba(5, 2, 12, 0.24), inset 0 1px 0 rgba(255, 255, 255, 0.16), inset 0 -2px 0 rgba(12, 7, 27, 0.66)",
  backdropFilter: "blur(14px)",
  WebkitBackdropFilter: "blur(14px)",
};

// Debounce hook
function useDebounce(value: string, delay: number) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

async function verifyPhone(phone: string): Promise<{ fullName: string; userId: string } | null> {
  try {
    // Get token from localStorage
    const token = localStorage.getItem("accessToken");
    
    if (!token) {
      console.error("No token found");
      return null;
    }

    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        get_person_function: {
          mobile: phone.replace(/^0/, ""), // Remove leading 0 if exists
        },
      }),
    });

    if (!response.ok) {
      return null;
    }

    const result = await response.json();
    
    if (result.state === 0 && result.data) {
      const data = JSON.parse(result.data);
      if (data.full_name && data.user_id) {
        return {
          fullName: data.full_name,
          userId: data.user_id,
        };
      }
    }

    return null;
  } catch (error) {
    console.error("Error verifying phone:", error);
    return null;
  }
}

function TeammateItem({
  teammate,
  canRemove,
  allTeammates,
  currentUserPhone,
  currentUserId,
  onRemove,
  onChange,
  onVerify,
}: {
  teammate: Teammate;
  canRemove: boolean;
  allTeammates: Teammate[];
  currentUserPhone: string;
  currentUserId: string;
  onRemove: () => void;
  onChange: (value: string) => void;
  onVerify: (fullName: string, userId: string, error?: string) => void;
}) {
  const [isVerifying, setIsVerifying] = useState(false);
  const [lastVerifiedPhone, setLastVerifiedPhone] = useState("");
  const debouncedPhone = useDebounce(teammate.phone, 1000);

  // Create a stable string of all phone numbers for dependency
  const allPhones = useMemo(() => {
    return allTeammates.map(t => t.phone).join(",");
  }, [allTeammates]);

  useEffect(() => {
    const verify = async () => {
      // Skip if already verified this phone
      if (debouncedPhone === lastVerifiedPhone) {
        return;
      }

      // Reset state when phone changes
      if (!debouncedPhone) {
        setLastVerifiedPhone("");
        return;
      }

      // Only verify if phone is valid (11 digits starting with 09)
      if (!/^09\d{9}$/.test(debouncedPhone)) {
        setLastVerifiedPhone("");
        return;
      }

      // بررسی شماره تکراری
      const duplicatePhone = allTeammates.find(
        (t) => t.id !== teammate.id && t.phone === debouncedPhone
      );
      if (duplicatePhone) {
        onVerify("", "", "این شماره قبلاً وارد شده است");
        setLastVerifiedPhone(debouncedPhone);
        return;
      }

      setIsVerifying(true);
      const result = await verifyPhone(debouncedPhone);
      setIsVerifying(false);

      if (result) {
        // بررسی شناسه کاربر - آیا کاربر در حال افزودن خودش است؟
        if (result.userId === currentUserId) {
          onVerify("", "", "شما نمی‌توانید خودتان را به عنوان عضو اضافه کنید");
          setLastVerifiedPhone(debouncedPhone);
          return;
        }
        
        onVerify(result.fullName, result.userId);
      } else {
        onVerify("", "", "کاربر یافت نشد");
      }
      
      setLastVerifiedPhone(debouncedPhone);
    };

    verify();
  }, [debouncedPhone, currentUserId, allPhones, teammate.id, lastVerifiedPhone]);

  const hasError = teammate.error || (teammate.fullName === "" && /^09\d{9}$/.test(teammate.phone));
  const isSuccess = teammate.fullName && !teammate.error;

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <div className="flex-1 relative">
          <input
            type="tel"
            value={teammate.phone}
            onChange={(e) => {
              const value = e.target.value;
              // فقط اجازه ورود اعداد
              if (value === "" || /^[0-9]*$/.test(value)) {
                onChange(value);
              }
            }}
            placeholder="۰۹۱۲۳۴۵۶۷۸۹"
            dir="ltr"
            maxLength={11}
            className="h-14 w-full rounded-full py-[12px] pl-[43px] pr-[48px] text-base text-white outline-none placeholder:text-white/45"
            style={inputStyle}
          />
          
          {/* Verification Status Icon */}
          <div className="absolute left-3 top-1/2 -translate-y-1/2">
            {isVerifying && (
              <Loader2 className="h-5 w-5 animate-spin text-[#D8B4FE]" />
            )}
            {!isVerifying && isSuccess && (
              <CheckCircle className="m-[0px] h-5 w-5 text-emerald-300" />
            )}
            {!isVerifying && hasError && (
              <XCircle className="h-5 w-5 text-rose-300" />
            )}
          </div>
        </div>

        {canRemove && (
          <motion.button
            type="button"
            whileTap={{ scale: 0.9 }}
            onClick={onRemove}
            className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
            style={{
              background: "linear-gradient(135deg, rgba(220, 38, 38, 0.85) 0%, rgba(185, 28, 28, 0.85) 100%)",
              boxShadow: "0 4px 12px rgba(220, 38, 38, 0.4)",
            }}
          >
            <X className="w-5 h-5 text-white" />
          </motion.button>
        )}
      </div>

      {/* User Name or Error Display */}
      {!isVerifying && isSuccess && (
        <div className="m-[0px] flex items-center gap-1 px-[8px] py-[0px] text-sm text-emerald-300">
          <span>✓</span>
          <span>{teammate.fullName}</span>
        </div>
      )}
      {!isVerifying && teammate.error && (
        <div className="flex items-center gap-1 px-2 text-sm text-rose-300">
          <span>✗</span>
          <span>{teammate.error}</span>
        </div>
      )}
      {!isVerifying && !teammate.error && teammate.fullName === "" && /^09\d{9}$/.test(teammate.phone) && (
        <div className="flex items-center gap-1 px-2 text-sm text-rose-300">
          <span>✗</span>
          <span>کاربر یافت نشد</span>
        </div>
      )}
    </div>
  );
}

export function TeammatesSection({ teammates, onAdd, onRemove, onChange, onVerify }: TeammatesSectionProps) {
  const [currentUserPhone, setCurrentUserPhone] = useState("");
  const [currentUserId, setCurrentUserId] = useState("");

  useEffect(() => {
    // دریافت شماره تلفن و شناسه کاربر فعلی ��ز پروفایل
    const profile = getCachedProfile();
    if (profile?.username) {
      setCurrentUserPhone(profile.username);
    }
    if (profile?.user_id) {
      setCurrentUserId(profile.user_id);
    }
  }, []);

  return (
    <div>
      <label className="mb-3 block text-sm font-bold text-[#FBE7F5]">شماره تلفن هم‌تیمی‌ها</label>
      <div className="space-y-3">
        {teammates.map((teammate) => (
          <TeammateItem
            key={teammate.id}
            teammate={teammate}
            canRemove={teammates.length > 1}
            allTeammates={teammates}
            currentUserPhone={currentUserPhone}
            currentUserId={currentUserId}
            onRemove={() => onRemove(teammate.id)}
            onChange={(value) => onChange(teammate.id, value)}
            onVerify={(fullName, userId, error) => onVerify(teammate.id, fullName, userId, error)}
          />
        ))}
        <motion.button
          type="button"
          whileTap={{ scale: 0.95 }}
          onClick={onAdd}
          className="w-full px-4 py-3 rounded-2xl text-white text-sm font-bold flex items-center justify-center gap-2"
          style={{
            background:
              "linear-gradient(135deg, rgba(168,115,255,0.28) 0%, rgba(138,82,238,0.24) 100%)",
            border: "1px dashed rgba(216, 180, 254, 0.65)",
          }}
        >
          <Plus className="w-5 h-5" />
          افزودن هم‌تیمی
        </motion.button>
      </div>
    </div>
  );
}
