import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useAppTheme } from '@theme';
import { CustomInput, PrimaryButton, ChipSelector } from '@components';
import { PersonIcon } from '@icons';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { OnBoardingParamList } from '@navigation/navigationTypes';
import { RouteNames } from '@utils/constants';
import { Gender, VehicleType } from '@interfaces';
import { getStyles } from './completeProfileScreen.styles';
import { useAppDispatch, useAppSelector } from '@store';
import { completeOnboard } from './thunk';

export const CompleteProfileScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation =
    useNavigation<NativeStackNavigationProp<OnBoardingParamList>>();

  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [vehicleNo, setVehicleNo] = useState('');
  const [gender, setGender] = useState<Gender | ''>('');
  const [vehicleType, setVehicleType] = useState<VehicleType | ''>('');
  // const [isLoading, setIsLoading] = useState(false);
  const dispatch = useAppDispatch();
  const { isLoading } = useAppSelector(state => state.onboard);

  const genderOptions = Object.values(Gender).map(v => ({
    label: v,
    value: v,
  }));
  const vehicleTypeOptions = Object.values(VehicleType || '').map(v => ({
    label: v,
    value: v,
  }));

  // const documents = [
  //   { id: 'dl', title: 'Driving License', sub: 'Verified', status: 'verified' },
  //   {
  //     id: 'aadhaar',
  //     title: 'Aadhaar Card',
  //     sub: 'Verified',
  //     status: 'verified',
  //   },
  //   { id: 'rc', title: 'Vehicle RC', sub: 'Verified', status: 'verified' },
  //   {
  //     id: 'insurance',
  //     title: 'Insurance Policy',
  //     sub: 'Expires on 12 May 2026',
  //     status: 'expiring',
  //   },
  // ];

  // const handleDocumentPress = (docTitle: string) => {
  //   Alert.alert('Document Details', `Viewing or uploading ${docTitle}...`);
  // };

  const handleSubmit = () => {
    if (!fullName || !email || !vehicleNo || !gender || !vehicleType) {
      Alert.alert(
        'Required Fields',
        'Please fill out all profile information including gender and vehicle type.',
      );
      return;
    }

    dispatch(
      completeOnboard({
        name: fullName,
        email: email,
        vehicleNumber: vehicleNo,
        gender: gender,
        vehicleType: vehicleType,
      }),
    )
      .unwrap()
      .then(() => {
        navigation.replace(RouteNames.Kyc);
      })
      .catch(error => {
        Alert.alert('Error', error.message);
      });
  };

  return (
    <View style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContainer}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.headerContainer}>
          <Text style={styles.title}>Complete Profile</Text>
          <Text style={styles.subtitle}>
            Enter details & upload documents to get verified
          </Text>
        </View>

        {/* Profile Avatar Upload Mock */}
        <View style={styles.profileImageContainer}>
          <TouchableOpacity
            style={styles.avatarPlaceholder}
            activeOpacity={0.8}
          >
            <PersonIcon size={40} color={colors.textSecondary} />
            <Text style={styles.avatarText}>Add Photo</Text>
            <View style={styles.cameraBadge}>
              <Text
                style={{
                  color: colors.white,
                  fontSize: 12,
                  fontWeight: 'bold',
                }}
              >
                +
              </Text>
            </View>
          </TouchableOpacity>
        </View>

        {/* Personal Details */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Personal Details</Text>
          <CustomInput
            label="Full Name"
            placeholder="Rahul Kumar"
            value={fullName}
            onChangeText={setFullName}
          />
          <CustomInput
            label="Email Address"
            placeholder="rahul.kumar@gmail.com"
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
          />
          <CustomInput
            label="Vehicle Number"
            placeholder="KA-01-MJ-8845"
            value={vehicleNo}
            onChangeText={setVehicleNo}
            autoCapitalize="characters"
          />
        </View>

        {/* Gender Selection */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Gender</Text>
          <ChipSelector
            options={genderOptions}
            selected={gender}
            onChange={(val: Gender) => setGender(val)}
          />
        </View>

        {/* Vehicle Type Selection */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Vehicle Type</Text>
          <ChipSelector
            options={vehicleTypeOptions}
            selected={vehicleType}
            onChange={(val: VehicleType) => setVehicleType(val)}
          />
        </View>

        {/* Required Documents Checklist */}
        {/* <View style={styles.section}>
          <Text style={styles.sectionTitle}>Required Documents</Text>
          {documents.map((doc) => (
            <TouchableOpacity
              key={doc.id}
              style={styles.documentItem}
              activeOpacity={0.7}
              onPress={() => handleDocumentPress(doc.title)}
            >
              <View style={styles.docLeft}>
                <ClipboardIcon size={22} color={colors.primary} />
                <View style={styles.docTextContainer}>
                  <Text style={styles.docTitle}>{doc.title}</Text>
                  <Text style={styles.docSub}>{doc.sub}</Text>
                </View>
              </View>

              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <View
                  style={[
                    styles.statusBadge,
                    {
                      backgroundColor:
                        doc.status === 'verified'
                          ? colors.primaryLight
                          : colors.warningLight,
                    },
                  ]}
                >
                  <Text
                    style={[
                      styles.statusText,
                      {
                        color:
                          doc.status === 'verified'
                            ? colors.primary
                            : colors.warning,
                      },
                    ]}
                  >
                    {doc.status === 'verified' ? 'VERIFIED' : 'ACTIVE'}
                  </Text>
                </View>
                <ChevronRightIcon size={20} color={colors.textSecondary} />
              </View>
            </TouchableOpacity>
          ))}
        </View> */}

        <PrimaryButton
          title="Submit & Verify"
          onPress={handleSubmit}
          isLoading={isLoading}
          style={styles.submitButton}
        />
      </ScrollView>
    </View>
  );
};

export default CompleteProfileScreen;
