import React, { useState } from "react";
import {
  View,
  ScrollView,
  Pressable,
  TextInput,
  ActivityIndicator,
  useColorScheme,
} from "react-native";
import { useSirouRouter } from "@sirou/react-native";
import { AppRoutes } from "@/lib/routes";
import { Text } from "@/components/ui/text";
import { Button } from "@/components/ui/button";
import { ScreenWrapper } from "@/components/ScreenWrapper";
import { ArrowLeft, User, Mail, Check } from "@/lib/icons";
import { useAuthStore } from "@/lib/auth-store";
import { api } from "@/lib/api";
import { toast } from "@/lib/toast-store";

export default function EditProfileScreen() {
  const nav = useSirouRouter<AppRoutes>();
  const { user, updateUser } = useAuthStore();
  const isDark = useColorScheme() === "dark";
  const iconColor = isDark ? "#94a3b8" : "#64748b";

  const [loading, setLoading] = useState(false);
  const [firstName, setFirstName] = useState(user?.firstName || "");
  const [lastName, setLastName] = useState(user?.lastName || "");

  const handleSave = async () => {
    if (!firstName.trim() || !lastName.trim()) {
      toast.error("Error", "First and last name are required");
      return;
    }

    setLoading(true);
    try {
      const response = await api.users.updateProfile({
        body: {
          firstName: firstName.trim(),
          lastName: lastName.trim(),
        },
      });
      updateUser(response);
      toast.success("Success", "Profile updated");
      nav.back();
    } catch (e: any) {
      toast.error("Error", e?.message || "Failed to update profile");
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenWrapper className="bg-background">
      <View className="px-6 pt-4 flex-row justify-between items-center">
        <Pressable
          onPress={() => nav.back()}
          className="h-10 w-10 rounded-[10px] bg-card items-center justify-center border border-border"
        >
          <ArrowLeft color={isDark ? "#fff" : "#0f172a"} size={20} />
        </Pressable>
        <Text className="text-foreground text-[17px] font-sans-bold tracking-tight">
          Edit Profile
        </Text>
        <View className="w-10" />
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{
          paddingHorizontal: 24,
          paddingTop: 32,
          paddingBottom: 40,
        }}
      >
        <View className="gap-6">
          <View>
            <Text className="text-[11px] font-sans-bold uppercase tracking-widest text-muted-foreground mb-2 ml-1">
              First Name
            </Text>
            <View className="flex-row items-center rounded-xl px-4 border border-border h-14">
              <User size={16} color={iconColor} />
              <TextInput
                className="flex-1 ml-3 text-foreground text-base"
                placeholder="Enter first name"
                placeholderTextColor={isDark ? "#475569" : "#94a3b8"}
                value={firstName}
                onChangeText={setFirstName}
                autoCorrect={false}
              />
              {firstName.trim().length > 0 && (
                <Check size={16} color="#10b981" />
              )}
            </View>
          </View>

          <View>
            <Text className="text-[11px] font-sans-bold uppercase tracking-widest text-muted-foreground mb-2 ml-1">
              Last Name
            </Text>
            <View className="flex-row items-center rounded-xl px-4 border border-border h-14">
              <User size={16} color={iconColor} />
              <TextInput
                className="flex-1 ml-3 text-foreground text-base"
                placeholder="Enter last name"
                placeholderTextColor={isDark ? "#475569" : "#94a3b8"}
                value={lastName}
                onChangeText={setLastName}
                autoCorrect={false}
              />
              {lastName.trim().length > 0 && (
                <Check size={16} color="#10b981" />
              )}
            </View>
          </View>

          {user?.email && (
            <View>
              <Text className="text-[11px] font-sans-bold uppercase tracking-widest text-muted-foreground mb-2 ml-1">
                Email
              </Text>
              <View className="flex-row items-center rounded-xl px-4 border border-border/50 h-14 bg-muted/20">
                <Mail size={16} color={iconColor} />
                <Text className="flex-1 ml-3 text-base text-muted-foreground">
                  {user.email}
                </Text>
              </View>
            </View>
          )}

          <View className="mt-4 gap-3">
            <Button
              className="h-12 bg-primary rounded-[8px]"
              onPress={handleSave}
              disabled={loading}
            >
              {loading ? (
                <ActivityIndicator color="white" />
              ) : (
                <Text className="text-white font-sans-bold text-sm  tracking-widest">
                  Save Changes
                </Text>
              )}
            </Button>

            <Pressable
              onPress={() => nav.back()}
              className="h-12 rounded-[8px] border border-border items-center justify-center"
              disabled={loading}
            >
              <Text className="text-muted-foreground font-sans-bold text-sm  tracking-widest">
                Cancel
              </Text>
            </Pressable>
          </View>
        </View>
      </ScrollView>
    </ScreenWrapper>
  );
}
