import {
  FocusAwareStatusBar,
  SafeAreaView,
  ScrollView,
  View,
} from '@/components/ui';
import * as React from 'react';
import {
  Keyboard,
  Text as RNText,
  TextInput,
  TouchableWithoutFeedback,
} from 'react-native';
import Button from '@/library/button';
import Label from '@/library/label';
import SocialButton from '@/library/social-button';
import TextField, { StatusConfig } from '@/library/textfield';
import TopNavigation from '@/library/top-navigation';
import Switch from '@/library/switch';
import { useSharedValue } from 'react-native-reanimated';
import CheckBox from '@/library/check-box';
import MainPageHeader from '@/library/main-page-header';
import SubPageHeader from '@/library/sub-page-header';
import Text from '@/library/text';
import IconButton from '@/library/icon-button';
import TestCircle from '@/library/icons/test-circle';
import { FullCircleIcon } from '@/library/icons/full-circle';
import { EmptyCircleIcon } from '@/library/icons/empty-circle';
import MenuItem from '@/library/menu-item';
import SearchBar from '@/library/search-bar';
import { LocationBlackShapeIcon } from '@/library/icons/location-black-shape';
import CommonModal from '@/library/popup-modal';
import showSnackBar, {
  dismissLoadingSnackBar,
  updateSnackBar,
} from '@/library/snack-bar';
import Check from '@/library/check';
import { ChevronDownIcon } from '@/library/icons/chevron-down';

const IconDummyComponent = () => {
  return <View className="w-6 h-6 bg-red-500 rounded-full" />;
};
const IconDummyComponent2 = () => {
  return <View className="w-6 h-6 bg-blue-500 rounded-full" />;
};

export default function Paper() {
  const [text, setText] = React.useState('');
  const [passwordText, setPasswordText] = React.useState('');
  const [passwordVisible, setPasswordVisible] = React.useState(true);
  const [countText, setCountText] = React.useState('');
  const [testToggle, setTestToggle] = React.useState(false);

  const searchBarRef = React.useRef<TextInput>(null);

  const [passwordStatusConfig, setPasswordStatusConfig] =
    React.useState<StatusConfig>({
      status: 'none',
      message: '',
    });
  const [statusConfig, setStatusConfig] = React.useState<StatusConfig>({
    status: 'none',
    message: '',
  });

  interface IdState {
    first: string;
    second: string;
  }

  const [idValue, setIdValue] = React.useState({ first: '', second: '' });
  const [idStatusConfig, setIdStatusConfig] = React.useState<StatusConfig>({
    status: 'none',
    message: '',
  });

  function handlePasswordChange(inputText: string) {
    setPasswordText(inputText);
    if (inputText.length >= 8) {
      setPasswordStatusConfig({
        status: 'success',
        message: '유효한 비밀번호입니다.',
      });
    } else {
      setPasswordStatusConfig({
        status: 'error',
        message: '비밀번호는 최소 8자 이상이어야 합니다.',
      });
    }
  }

  function handlePasswordClear() {
    setPasswordText('');
    setPasswordStatusConfig({
      status: 'none',
      message: '',
    });
  }

  const handleIdChange = {
    onFirstChange: (text: string) => {
      setIdValue((prev) => ({
        ...prev,
        first: text,
      }));
      validateId(text, idValue.second);
    },
    onSecondChange: (text: string) => {
      setIdValue((prev) => ({
        ...prev,
        second: text,
      }));
      validateId(idValue.first, text);
    },
  };

  function validateId(first: string, second: string) {
    // ID 유효성 검사: 앞 6자리, 뒤 1자리
    if (first.length === 6 && second.length === 1) {
      setIdStatusConfig({
        status: 'success',
        message: '유효한 주민등록번호입니다.',
      });
    } else {
      setIdStatusConfig({
        status: 'error',
        message: '앞 6자리와 뒤 1자리를 입력해야 합니다.',
      });
    }
  }

  function handleClear() {
    setIdValue({ first: '', second: '' });
    setIdStatusConfig({
      status: 'none',
      message: '',
    });
  }

  const handleCustomValidation = (text: string) => {
    if (text.length <= 10 && /^[a-zA-Z]*$/.test(text)) {
      // 예: 10자 이하, 알파벳만 허용
      setCountText(text);
    }
  };

  // Top Navigation
  const TestComponent = () => {
    return <View className="w-[24px] h-[24px] bg-blue-500 rounded-full" />;
  };

  const [activeTab, setActiveTab] = React.useState('테스트');

  // Switch
  const isOn = useSharedValue(true);

  const handlePress = () => {
    isOn.value = !isOn.value;
    setTestToggle((prev) => !prev);
    console.log(isOn.value);
  };

  // checkbox
  const [checked, setChecked] = React.useState(true);

  const handleTextChange = (inputText: string) => {
    setText(inputText);
    if (inputText.length < 3) {
      setStatusConfig({
        status: 'error',
        message: '에러 메시지 표기',
      });
    } else {
      // 상황에 따라 성공 표기를 하고싶지 않다면, status는 'none'으로 설정, message는 ''로 설정
      setStatusConfig({
        status: 'success',
        message: '성공 메시지 표기',
      });
    }
  };

  const [searchText, setSearchText] = React.useState('');
  const handleSearch = () => {
    console.log(searchText, 'submit');
  };

  const [isVisible, setIsVisible] = React.useState(false);

  const [loading, setLoading] = React.useState(false);
  const [isChecked, setIsChecked] = React.useState(false);

  return (
    <TopNavigation backgroundColor="white" barStyle={'dark-content'}>
      <MainPageHeader
        tabTitle={['테스트', '테스트2']}
        // tabTitle={['테스트']}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        funcComponent={[
          <IconButton
            required={true}
            icon={<TestCircle />}
            onPress={() => {
              console.log('CLICK');
              searchBarRef.current?.blur();
            }}
          />,
        ]}
      />
      {/* <SubPageHeader
        title={'Middle Title'}
        subTitle={'보조하는 텍스트 (옵션)'}
        subContent={'타이틀은 최대 두줄까지만\n입력하세요.'}
        exitEvent={() => console.log('exit')}
        exitIcon={<TestCircle />}
        funcComponent={[
          <IconButton
            required={true}
            icon={<TestCircle />}
            onPress={() => console.log('CLICK1')}
          />,
          <IconButton
            required={true}
            icon={<TestCircle />}
            onPress={() => console.log('CLICK2')}
          />,
          <IconButton
            // required={true}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 40 }}
            icon={<TestCircle />}
            onPress={() => console.log('CLICK3')}
          />,
        ]}
      /> */}
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View className="justify-center gap-4 px-[16px]">
          {activeTab === '테스트' && (
            <View>
              <Text
                face={'title'}
                size="xlarge"
                weight="bold"
                textColor={`black`}
              >
                {'텍스트'}
              </Text>
              {/* 정적 라벨 */}
              <Label
                value={'라벨 텍스트'}
                labelClassName="text-sm"
                isLabelOnly
                required
              />

              <MenuItem
                activeIcon={<FullCircleIcon />}
                idleIcon={<EmptyCircleIcon />}
                menuTitle={'타이틀'}
                selected={testToggle}
                badge={{ variant: 'dot' }}
              />

              <FullCircleIcon />
              <EmptyCircleIcon />

              <Text face={'display'} size="small">
                Display small
              </Text>
              <Text face={'display'} size="medium">
                Display medium
              </Text>
              <Text face={'display'} size="large">
                Display large
              </Text>
              <Text face={'display'} size="xlarge" textColor="gray-400">
                Display xlarge
              </Text>

              {/* 카운팅 라벨 */}
              <Label
                value={countText}
                onChangeText={handleCustomValidation}
                labelClassName="text-lg"
                characterCount={true}
                maxCharacterCount={10}
              />

              <CheckBox
                // backgroundColor={'orange'}
                // backgroundColor={'red'}
                // disabled={true}
                backgroundColor={'brand-primary-default'}
                className="rounded-full"
                checked={checked}
                onChange={() => {
                  console.log(!checked ? 'checked' : 'unchecked');
                  setChecked(!checked);
                }}
              />
              <Switch
                trackColors={{ on: '#10B981', off: '#E5E7EB' }}
                // disabled={true}
                value={isOn}
                onPress={handlePress}
                style={{ width: 42, height: 24, padding: 3 }}
              />
              <View
                style={{
                  backgroundColor: 'green',
                  // justifyContent: 'center',
                  flexDirection: 'row',
                }}
              >
                <Text
                  face={'paragraph'}
                  size="2xlarge"
                  // textColor={'brand-primary-default'}
                  weight={'extrabold'}
                  className="py-[10px] bg-red-500"
                >
                  paragraph 2xlarge
                </Text>
              </View>
              <RNText style={{ backgroundColor: 'yellow' }}>??????</RNText>

              {/* <RNText className="text-prime-text-10">text-Prime Text 10</RNText>
              <RNText className="text-prime-text-12">text-Prime Text 12</RNText>
              <RNText className="text-prime-text-14">text-Prime Text 14</RNText>
              <RNText className="text-prime-text-16">text-Prime Text 16</RNText>
              <RNText className="text-prime-text-20">text-Prime Text 20</RNText>
              <RNText className="text-prime-text-24">text-Prime Text 24</RNText>
              <RNText className="text-prime-text-32">text-Prime Text 32</RNText>
              <RNText className="text-prime-paragraph-13">
                text-prime-paragraph-13
              </RNText>
              <RNText className="text-prime-paragraph-14">
                text-prime-paragraph-14
              </RNText>
              <RNText className="text-prime-paragraph-15">
                text-prime-paragraph-15
              </RNText>
              <RNText className="text-prime-paragraph-16">
                text-prime-paragraph-16
              </RNText>
              <RNText className="text-prime-paragraph-18">
                text-prime-paragraph-18
              </RNText> */}
            </View>
          )}
          {activeTab === '테스트2' && (
            <>
              <SearchBar
                ref={searchBarRef}
                backgroundColor={'#F3F4F6'}
                value={searchText}
                onChangeText={setSearchText}
                onClear={() => setSearchText('')}
                onSubmit={handleSearch}
                placeholder={'검색어를 입력해주세요.'}
                onFocus={() => console.log('focus')}
                onBlur={() => console.log('blur')}
                blurIcon={false ? <LocationBlackShapeIcon /> : null}
              />
              <TextField
                label={{
                  text: '라벨',
                  className: 'text-sm',
                }}
                input={{
                  mode: 'default',
                  value: text,
                  placeholder: '홍길동',
                }}
                statusConfig={statusConfig}
                onClear={() => {
                  setText('');
                  setStatusConfig({
                    status: 'none',
                    message: '',
                  });
                }}
                onChangeText={handleTextChange}
              />
              <TextField
                label={{
                  text: '비밀번호',
                }}
                input={{
                  mode: 'password',
                  value: passwordText,
                  placeholder: '비밀번호',
                  isSecureTextEntry: passwordVisible,
                  onSecureTextEntryChange: setPasswordVisible,
                }}
                statusConfig={passwordStatusConfig}
                onChangeText={handlePasswordChange}
                onClear={handlePasswordClear}
              />
              <CommonModal
                isVisible={isVisible}
                mainTitle="업데이트 안내"
                subTitle="보다 좋은 서비스를 위해 새 버전을 이용해주세요."
                onClose={() => setIsVisible(false)}
                onConfirm={() => console.log('confirm')}
                cancelButton={{
                  text: '취소',
                  variant: 'danger',
                  shape: 'pill',
                  className: 'flex-1',
                }}
                confirmButton={{
                  text: '확인',
                  variant: 'dangerLow',
                  shape: 'pill',
                  className: 'flex-1',
                }}
              />

              {/* <CommonModal
                isVisible={isVisible}
                mainTitle="알림"
                subTitle="처리가 완료되었습니다."
                onClose={() => setIsVisible(false)}
              /> */}
              <View className="flex-row gap-4  w-full">
                <Button
                  // disabled={true}
                  // loading={true}
                  variant="outlined"
                  text={'테스트LEFT'}
                  shape="pill"
                  className="flex-1"
                  leftIcon={{
                    icon: <TestCircle />,
                    gap: 4,
                  }}
                  // backgroundColor={'brand-primary-default'}
                  // textColor={'blue'}
                  // onPress={() => setIsVisible(true)}
                  onPress={() => {
                    setLoading(false);
                  }}
                />
                <Button
                  // disabled={true}
                  // loading={true}
                  variant="primaryLow"
                  text={'스낵바테스트'}
                  className="flex-1"
                  shape={'round'}
                  // backgroundColor={'brand-primary-default'}
                  // textColor={'blue'}
                  // onPress={() => console.log('테스트')}
                  onPress={() => {
                    // showSnackBar({
                    //   styleTheme: 'dark',
                    //   variant: 'thumbnail',
                    //   thumbnailProps: {
                    //     imageUrl: 'https://placehold.co/600x400',
                    //     title: '타이틀',
                    //     description: '설명',
                    //   },
                    //   className: 'mb-[42px]',
                    //   rightTextButton: true,
                    //   buttonText: '보기',
                    // });
                    // dismissLoadingSnackBar();
                    showSnackBar({
                      variant: 'success',
                      message: '변경되었어요2.',
                      className: 'mb-[48px]',
                    });
                  }}
                />
              </View>
              <Button
                // disabled={true}
                // loading={true}
                variant="primaryLow"
                text={'테스트!!!!'}
                shape={'round'}
                // backgroundColor={'brand-primary-default'}
                // textColor={'blue'}
                onPress={() => {
                  // showSnackBar({
                  //   message: 'AI 답변 생성중...',
                  //   styleTheme: 'dark',
                  //   loading: true,
                  // });

                  showSnackBar({
                    variant: 'success',
                    message: '변경되었어요.',
                    className: 'mb-[48px]',
                  });

                  // setLoading(true);

                  // // 로딩 시작 시 스낵바 표시
                  // showSnackBar({
                  //   message: 'AI 답변 생성중..!!!.',
                  //   styleTheme: 'dark',
                  //   loading: true,
                  // });

                  // // 작업 완료 후
                  // setTimeout(() => {
                  //   setLoading(false);

                  //   // updateSnackBar 사용
                  //   updateSnackBar({
                  //     variant: 'success',
                  //     message: '생성 완료',
                  //     styleTheme: 'dark',
                  //     loading: false,
                  //     duration: 5000,
                  //   });
                  // }, 1500);
                }}
              />
              <SocialButton
                type="google"
                onPress={() => console.log('카카오 로그인')}
              />
            </>
          )}

          <Check
            checked={isChecked}
            disabled={false}
            onPress={() => setIsChecked(!isChecked)}
          />
        </View>
      </TouchableWithoutFeedback>
    </TopNavigation>
  );
}
