import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import InputGroup from "@/components/auth/InputGroup";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { showToast } from "@/utils/toast";
import { EnvelopeIcon, PencilSimpleIcon, PhoneIcon } from "phosphor-react-native";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { KeyboardAvoidingView, Platform, ScrollView, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

interface ContactFormData {
  phone: string;
}

export default function ContactInformationScreen() {
  const { user, getUser } = useAuthStore((state) => state);
  const { primary } = useColor();
  const [isEditing, setIsEditing] = useState(false);

  const {
    control,
    handleSubmit,
    formState: { errors: formErrors },
    reset,
  } = useForm<ContactFormData>({
    defaultValues: {
      phone: user?.phone || "",
    },
  });

  const {
    mutate: updateContact,
    isLoading,
    backendErrors,
  } = useQueryMutation({
    url: "/client/profile/phone",
    isUpdateMethod: true,
  });

  const onSubmit = handleSubmit((data) => {
    updateContact(
      { phone: data.phone },
      {
        onSuccess: (res) => {
          showToast({
            type: "success",
            text: res?.message || "Contact information updated successfully",
          });
          getUser();
          setIsEditing(false);
        },
      },
    );
  });

  const handleCancel = () => {
    reset({ phone: user?.phone || "" });
    setIsEditing(false);
  };

  return (
    <SafeAreaView className="bg-white h-full">
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={{ flex: 1 }}>
        <ScrollView keyboardShouldPersistTaps="handled" className="px-4">
          <BackButtonTitle title="Contact Information" />

          {/* Header with Edit button */}
          <View className="flex-row items-center justify-between mt-6 mb-4">
            <Text className="text-lg font-manrope-bold text-slate-900">Your Contact Details</Text>
            {!isEditing && (
              <TouchableOpacity
                onPress={() => setIsEditing(true)}
                className="flex-row items-center gap-1.5 px-4 py-2 rounded-xl border border-slate-200"
                activeOpacity={0.7}
              >
                <View pointerEvents="none">
                  <PencilSimpleIcon size={16} color={primary.base} />
                </View>
                <Text className="text-sm font-manrope-bold" style={{ color: primary.base }}>Edit</Text>
              </TouchableOpacity>
            )}
          </View>

          <View className="gap-y-4">
            {/* Email - Always read-only */}
            <View className="p-5 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: `${primary.base}15` }}
                  >
                    <EnvelopeIcon size={22} color={primary.base} weight="fill" />
                  </View>
                  <View className="flex-1">
                    <Text className="text-xs font-manrope text-slate-400 uppercase tracking-wide">
                      Email Address
                    </Text>
                    <Text className="text-[16px] font-manrope-bold text-slate-800 mt-1">
                      {user?.email || "Not set"}
                    </Text>
                  </View>
                </View>
                <VerifiedBadge isVerified={!!user?.email_verified_at} />
              </View>
            </View>

            {/* Phone - Editable */}
            {isEditing ? (
              <View className="p-5 rounded-2xl border-2 border-slate-200 bg-white">
                <View className="flex-row items-center gap-2 mb-4">
                  <PhoneIcon size={18} color={primary.base} weight="fill" />
                  <Text className="text-sm font-manrope-bold text-slate-700">Edit Phone Number</Text>
                </View>
                <InputGroup
                  control={control}
                  label="Phone Number"
                  name="phone"
                  error={formErrors.phone}
                  backendError={backendErrors?.phone}
                />
                <View className="flex-row gap-3 mt-4">
                  <View className="flex-1">
                    <Button onPress={handleCancel} text="Cancel" type="secondary" />
                  </View>
                  <View className="flex-1">
                    <Button onPress={onSubmit} isLoading={isLoading} text="Save" />
                  </View>
                </View>
              </View>
            ) : (
              <View className="p-5 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: "#fef9c3" }}
                    >
                      <PhoneIcon size={22} color="#ca8a04" weight="fill" />
                    </View>
                    <View className="flex-1">
                      <Text className="text-xs font-manrope text-slate-400 uppercase tracking-wide">
                        Phone Number
                      </Text>
                      <Text className="text-[16px] font-manrope-bold text-slate-800 mt-1">
                        {user?.phone || "Not set"}
                      </Text>
                    </View>
                  </View>
                  <VerifiedBadge isVerified={!!user?.phone_verified_at} />
                </View>
              </View>
            )}

            {/* Country */}
            {user?.country_name && (
              <View className="p-5 rounded-2xl border border-slate-100 bg-slate-50">
                <View className="flex-row items-center gap-4">
                  <View
                    className="w-12 h-12 rounded-xl items-center justify-center"
                    style={{ backgroundColor: "#e0e7ff" }}
                  >
                    <Text className="text-xl">🌍</Text>
                  </View>
                  <View className="flex-1">
                    <Text className="text-xs font-manrope text-slate-400 uppercase tracking-wide">
                      Country
                    </Text>
                    <Text className="text-[16px] font-manrope-bold text-slate-800 mt-1">
                      {user.country_name}
                    </Text>
                  </View>
                </View>
              </View>
            )}

            {/* Address Info */}
            {(user?.address || user?.city || user?.zip_code) && (
              <View
                className="p-5 rounded-2xl border border-slate-100"
                style={{ backgroundColor: primary[5] }}
              >
                <Text className="text-sm font-manrope-bold text-slate-700 mb-3">
                  Address Details
                </Text>
                <View className="gap-y-2">
                  {user?.address && <InfoRow label="Address" value={user.address} />}
                  {user?.city && <InfoRow label="City" value={user.city} />}
                  {user?.zip_code && <InfoRow label="Zip Code" value={user.zip_code} />}
                </View>
              </View>
            )}
          </View>

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

function VerifiedBadge({ isVerified }: { isVerified: boolean }) {
  return (
    <View
      className="px-3 py-1.5 rounded-lg"
      style={{ backgroundColor: isVerified ? "#dcfce7" : "#fee2e2" }}
    >
      <Text
        className="text-xs font-manrope-bold"
        style={{ color: isVerified ? "#16a34a" : "#dc2626" }}
      >
        {isVerified ? "Verified" : "Unverified"}
      </Text>
    </View>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <View className="flex-row justify-between items-center">
      <Text className="text-sm font-manrope text-slate-500">{label}</Text>
      <Text className="text-sm font-manrope-bold text-slate-800">{value}</Text>
    </View>
  );
}
