import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import {
  CheckCircleIcon,
  EnvelopeIcon,
  IdentificationCardIcon,
  PhoneIcon,
  ShieldCheckIcon,
  XCircleIcon,
} from "phosphor-react-native";
import { ActivityIndicator, ScrollView, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function VerificationStatusScreen() {
  const { user } = useAuthStore((state) => state);
  const { primary } = useColor();

  const { mutate: sendOtp, isLoading: isSendingOtp } = useQueryMutation({
    url: "/send-otp",
    isPublic: true,
  });

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return null;
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  const handleEmailVerification = () => {
    sendOtp(
      { type: "email", email: user?.email },
      {
        onSuccess: (response) => {
          showToast({
            type: "success",
            text: response?.message || "OTP sent to your email",
          });
          // Navigate to OTP verification screen with email param
          router.push({
            pathname: "/(auth)/verify-email-mobile",
            params: { email: user?.email },
          });
        },
        onError: () => {
          showToast({
            type: "error",
            text: "Failed to send verification email",
          });
        },
      },
    );
  };

  const handlePhoneVerification = () => {
    if (!user?.phone) {
      showToast({ type: "error", text: "Please add a phone number first" });
      router.push("/contact-information");
      return;
    }
    sendOtp(
      { type: "phone", phone: user.phone },
      {
        onSuccess: (response) => {
          showToast({
            type: "success",
            text: response?.message || "OTP sent to your phone",
          });
          // Navigate to OTP verification screen with phone param
          router.push({
            pathname: "/(auth)/verify-email-mobile",
            params: { phone: user?.phone },
          });
        },
        onError: () => {
          showToast({
            type: "error",
            text: "Failed to send verification SMS",
          });
        },
      },
    );
  };

  return (
    <ScrollView className="bg-white px-4">
      <SafeAreaView>
        <BackButtonTitle title="Verification Status" />

        <View className="mt-6 gap-y-4">
          {/* Email Verification */}
          <StatusItem
            icon={
              <EnvelopeIcon
                size={22}
                color={user?.email_verified_at ? "#16a34a" : "#9ca3af"}
                weight="fill"
              />
            }
            title="Email Verification"
            isVerified={!!user?.email_verified_at}
            detail={
              user?.email_verified_at
                ? formatDate(user.email_verified_at)
                : "Not verified"
            }
            bgColor={user?.email_verified_at ? "#dcfce7" : "#f3f4f6"}
            action={
              !user?.email_verified_at ? (
                <ActionButton
                  label="Verify"
                  onPress={handleEmailVerification}
                  isLoading={isSendingOtp}
                  color={primary.base}
                  disabled={!user?.email}
                />
              ) : undefined
            }
          />

          {/* Phone Verification */}
          <StatusItem
            icon={
              <PhoneIcon
                size={22}
                color={user?.phone_verified_at ? "#16a34a" : "#9ca3af"}
                weight="fill"
              />
            }
            title="Phone Verification"
            isVerified={!!user?.phone_verified_at}
            detail={
              user?.phone
                ? user.phone_verified_at
                  ? formatDate(user.phone_verified_at)
                  : "Not verified"
                : "Not set"
            }
            bgColor={user?.phone_verified_at ? "#dcfce7" : "#f3f4f6"}
            action={
              !user?.phone_verified_at ? (
                <ActionButton
                  label={user?.phone ? "Verify" : "Add Phone"}
                  onPress={
                    user?.phone
                      ? handlePhoneVerification
                      : () => router.push("/contact-information")
                  }
                  isLoading={isSendingOtp}
                  color={primary.base}
                />
              ) : undefined
            }
          />

          {/* KYC Verification */}
          <StatusItem
            icon={
              <IdentificationCardIcon
                size={22}
                color={
                  user?.is_kyc_verified
                    ? "#16a34a"
                    : user?.kyc_status === "rejected"
                      ? "#dc2626"
                      : user?.kyc_status === "pending"
                        ? "#d97706"
                        : "#9ca3af"
                }
                weight="fill"
              />
            }
            title="KYC Verification"
            isVerified={!!user?.is_kyc_verified}
            detail={
              user?.is_kyc_verified
                ? "Verified"
                : user?.kyc_status === "pending"
                  ? "Under Review"
                  : user?.kyc_status === "rejected"
                    ? "Rejected" + (user?.kyc?.reason ? `: ${user.kyc.reason}` : "")
                    : "Not verified"
            }
            bgColor={
              user?.is_kyc_verified
                ? "#dcfce7"
                : user?.kyc_status === "rejected"
                  ? "#fee2e2"
                  : user?.kyc_status === "pending"
                    ? "#fef3c7"
                    : "#f3f4f6"
            }
            action={
              !user?.is_kyc_verified && user?.kyc_status !== "pending" ? (
                <ActionButton
                  label={user?.kyc_status === "rejected" ? "Resubmit" : "Submit KYC"}
                  onPress={() => {
                    router.push("/(auth)/kyc");
                  }}
                  color={primary.base}
                />
              ) : undefined
            }
          />
        </View>

        {/* Summary Card */}
        <View
          className="mt-8 p-5 rounded-2xl border border-slate-100"
          style={{ backgroundColor: primary[5] }}
        >
          <View className="flex-row items-center gap-2 mb-3">
            <ShieldCheckIcon size={20} color={primary.base} weight="fill" />
            <Text className="text-[15px] font-manrope-bold text-slate-800">
              Verification Summary
            </Text>
          </View>
          <Text className="text-sm font-manrope text-slate-500 leading-5">
            Complete all verifications to unlock full platform features including
            investing, withdrawals, and marketplace access.
          </Text>
          <View className="flex-row gap-3 mt-4">
            <SummaryBadge label="Email" isVerified={!!user?.email_verified_at} />
            <SummaryBadge label="Phone" isVerified={!!user?.phone_verified_at} />
            <SummaryBadge label="KYC" isVerified={!!user?.is_kyc_verified} />
          </View>
        </View>

        <View className="h-10" />
      </SafeAreaView>
    </ScrollView>
  );
}

function ActionButton({
  label,
  onPress,
  isLoading,
  color,
  disabled,
}: {
  label: string;
  onPress: () => void;
  isLoading?: boolean;
  color: string;
  disabled?: boolean;
}) {
  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={isLoading || disabled}
      className="px-4 py-2.5 rounded-xl"
      style={{ backgroundColor: disabled ? "#d1d5db" : color, opacity: isLoading ? 0.7 : 1 }}
      activeOpacity={0.7}
    >
      {isLoading ? (
        <ActivityIndicator size="small" color="#fff" />
      ) : (
        <Text className="text-xs font-manrope-bold text-white">
          {label}
        </Text>
      )}
    </TouchableOpacity>
  );
}

function StatusItem({
  icon,
  title,
  isVerified,
  detail,
  bgColor,
  action,
}: {
  icon: React.ReactNode;
  title: string;
  isVerified: boolean;
  detail?: string | null;
  bgColor: string;
  action?: React.ReactNode;
}) {
  return (
    <View className="p-4 rounded-2xl border border-slate-100 bg-slate-50">
      <View className="flex-row items-center justify-between">
        <View className="flex-row items-center gap-4 flex-1">
          <View
            className="w-12 h-12 rounded-xl items-center justify-center"
            style={{ backgroundColor: bgColor }}
          >
            {icon}
          </View>
          <View className="flex-1">
            <Text className="text-[16px] font-manrope-bold text-slate-800">
              {title}
            </Text>
            <Text
              className={`text-sm font-manrope mt-0.5 ${isVerified ? "text-slate-500" : "text-red-500"}`}
            >
              {detail || (isVerified ? "Verified" : "Not verified")}
            </Text>
          </View>
        </View>
        {isVerified && !action ? (
          <View
            className="w-10 h-10 rounded-full items-center justify-center"
            style={{ backgroundColor: "#dcfce7" }}
          >
            <CheckCircleIcon size={22} color="#16a34a" weight="fill" />
          </View>
        ) : (
          action
        )}
      </View>
    </View>
  );
}

function SummaryBadge({
  label,
  isVerified,
}: {
  label: string;
  isVerified: boolean;
}) {
  return (
    <View
      className="flex-1 py-2.5 rounded-xl items-center justify-center"
      style={{ backgroundColor: isVerified ? "#dcfce7" : "#fee2e2" }}
    >
      <Text
        className="text-xs font-manrope-bold"
        style={{ color: isVerified ? "#16a34a" : "#dc2626" }}
      >
        {label}
      </Text>
      <Text
        className="text-[10px] font-manrope mt-0.5"
        style={{ color: isVerified ? "#16a34a" : "#dc2626" }}
      >
        {isVerified ? "✓ Done" : "✗ Pending"}
      </Text>
    </View>
  );
}
