import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useEffect, useRef, useState } from 'react';
import {
  Alert,
  Dimensions,
  PanResponder,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  UIManager,
  View,
  findNodeHandle,
} from 'react-native';
import { CodeField, Cursor } from 'react-native-confirmation-code-field';
import { SafeAreaView } from 'react-native-safe-area-context';
import Svg, { Line } from 'react-native-svg';

const LOCK_ENABLED = 'LOCK_ENABLED';
const LOCK_TYPE = 'LOCK_TYPE';
const LOCK_PASSWORD = 'LOCK_PASSWORD';
const LOCK_PATTERN = 'LOCK_PATTERN';

type LockType = 'pin' | 'password' | 'pattern';

type PatternLockProps = {
  path: number[];
  setPath: React.Dispatch<React.SetStateAction<number[]>>;
  onPatternComplete: (pattern: string | null) => void;
  patternError?: boolean;
};

const PatternLock = ({
  path,
  setPath,
  onPatternComplete,
  patternError,
}: PatternLockProps) => {
  const { width } = Dimensions.get('window');
  const size = width * 0.8;
  const cellSize = size / 3;
  const containerRef = useRef<View>(null);
  const [layout, setLayout] = useState({ pageX: 0, pageY: 0 });
  const [currentPos, setCurrentPos] = useState<{ x: number; y: number } | null>(
    null,
  );

  const points = Array.from({ length: 9 }, (_, i) => ({
    id: i + 1,
    x: (i % 3) * cellSize + cellSize / 2,
    y: Math.floor(i / 3) * cellSize + cellSize / 2,
  }));

  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onMoveShouldSetPanResponder: () => true,
    onPanResponderGrant: () => {
      setPath([]); // yangi chizma
      setCurrentPos(null);
    },
    onPanResponderMove: (_e, gestureState) => {
      const x = gestureState.moveX - layout.pageX;
      const y = gestureState.moveY - layout.pageY;
      setCurrentPos({ x, y });

      const point = points.find(
        p =>
          Math.abs(p.x - x) < cellSize / 3 && Math.abs(p.y - y) < cellSize / 3,
      );

      if (point && !path.includes(point.id)) {
        setPath(prev => {
          const newPath = [...prev, point.id];
          return newPath;
        });
      }
    },
    onPanResponderRelease: () => {
      setCurrentPos(null);
      onPatternComplete(path.length > 0 ? path.join('') : null);
    },
  });

  useEffect(() => {
    if (containerRef.current) {
      const handle = findNodeHandle(containerRef.current);
      if (handle) {
        UIManager.measure(handle, (_x, _y, _w, _h, pageX, pageY) => {
          setLayout({ pageX, pageY });
        });
      }
    }
  }, []);

  return (
    <View
      ref={containerRef}
      style={[styles.patternContainer, { width: size, height: size }]}
      {...panResponder.panHandlers}
    >
      <Svg style={StyleSheet.absoluteFill}>
        {path.map((id, idx) => {
          if (idx === 0) return null;
          const from = points.find(p => p.id === path[idx - 1]);
          const to = points.find(p => p.id === id);
          if (!from || !to) return null;
          return (
            <Line
              key={`${from.id}-${to.id}`}
              x1={from.x}
              y1={from.y}
              x2={to.x}
              y2={to.y}
              stroke="#28A7E8"
              strokeWidth={4}
            />
          );
        })}

        {currentPos && path.length > 0 && (
          <Line
            x1={points.find(p => p.id === path[path.length - 1])?.x}
            y1={points.find(p => p.id === path[path.length - 1])?.y}
            x2={currentPos.x}
            y2={currentPos.y}
            stroke="#28A7E8"
            strokeWidth={2}
            strokeDasharray="4"
          />
        )}
      </Svg>

      {points.map(point => (
        <View
          key={point.id}
          style={[
            styles.patternPoint,
            path.includes(point.id)
              ? patternError
                ? styles.patternPointError
                : styles.patternPointActive
              : {},
            { left: point.x - 15, top: point.y - 15 },
          ]}
        />
      ))}
    </View>
  );
};

const AddedLock = () => {
  const [step, setStep] = useState<1 | 2>(1);

  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  // Pattern states
  const [patternPath, setPatternPath] = useState<number[]>([]);
  const [patternTemp, setPatternTemp] = useState<string | null>(null);
  const [patternConfirmed, setPatternConfirmed] = useState(false);
  const [patternError, setPatternError] = useState(false);

  const route = useRoute<any>();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const paramLockType = route.params?.lockType;
  const validLockTypes: LockType[] = ['pin', 'password', 'pattern'];
  const initialLockType: LockType = validLockTypes.includes(paramLockType)
    ? paramLockType
    : 'pin';

  const [lockType] = useState<LockType>(initialLockType);

  const onContinue = async () => {
    if (step === 1) {
      if (lockType === 'pattern') {
        if (!patternTemp) {
          return Alert.alert('Error', 'Please draw your pattern first');
        }
        setPatternPath([]); // clear for second step
      } else {
        if (!password) {
          return Alert.alert('Error', 'Please enter your PIN/Password');
        }
      }
      setStep(2);
      return;
    }

    if (lockType === 'pattern') {
      if (!patternConfirmed) {
        return Alert.alert('Error', 'Please confirm your pattern');
      }
      await AsyncStorage.setItem(LOCK_PATTERN, patternTemp!);
    } else {
      if (!confirmPassword) {
        return Alert.alert('Error', 'Please confirm your PIN/Password');
      }
      if (password !== confirmPassword) {
        return Alert.alert('Error', 'Values do not match');
      }
      await AsyncStorage.setItem(LOCK_PASSWORD, password);
    }

    await AsyncStorage.setItem(LOCK_ENABLED, 'true');
    await AsyncStorage.setItem(LOCK_TYPE, lockType);
    Alert.alert('Success', 'Lock settings saved');

    resetForm();
    navigation.goBack();
  };

  const resetForm = () => {
    setStep(1);
    setPassword('');
    setConfirmPassword('');
    setPatternPath([]);
    setPatternTemp(null);
    setPatternConfirmed(false);
  };

  const handlePatternComplete = (inputPattern: string | null) => {
    if (!inputPattern || inputPattern.length < 4) {
      setPatternError(true);
      setTimeout(() => {
        setPatternError(false);
        setPatternPath([]);
      }, 800);
      return;
    }

    if (step === 1) {
      setPatternTemp(inputPattern);
    } else {
      if (patternTemp && inputPattern === patternTemp) {
        setPatternConfirmed(true);
        Alert.alert('Success', 'Pattern confirmed');
      } else {
        setPatternError(true);
        setTimeout(() => {
          setPatternError(false);
          setStep(1);
          setPatternPath([]);
        }, 800);
      }
    }
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <View style={styles.lockCard}>
          {lockType === 'pattern' ? (
            <View style={{ alignItems: 'center' }}>
              {step === 1 ? (
                <>
                  <Text style={{ textAlign: 'center', marginBottom: 10 }}>
                    Draw your pattern
                  </Text>
                  <PatternLock
                    path={patternPath}
                    setPath={setPatternPath}
                    onPatternComplete={handlePatternComplete}
                    patternError={patternError}
                  />
                </>
              ) : (
                <>
                  <Text style={{ textAlign: 'center', marginBottom: 10 }}>
                    Confirm your pattern
                  </Text>
                  <PatternLock
                    path={patternPath}
                    setPath={setPatternPath}
                    onPatternComplete={handlePatternComplete}
                  />
                </>
              )}
            </View>
          ) : lockType === 'pin' ? (
            <>
              {step === 1 ? (
                <>
                  <Text style={{ textAlign: 'center', marginBottom: 10 }}>
                    Enter PIN
                  </Text>
                  <CodeField
                    value={password}
                    onChangeText={setPassword}
                    cellCount={4}
                    rootStyle={{ marginBottom: 20 }}
                    keyboardType="number-pad"
                    renderCell={({ index, symbol, isFocused }) => (
                      <View
                        key={index}
                        style={[
                          styles.pinCell,
                          isFocused && styles.pinCellFocused,
                        ]}
                      >
                        <Text style={{ fontSize: 24 }}>
                          {symbol || (isFocused ? <Cursor /> : null)}
                        </Text>
                      </View>
                    )}
                  />
                </>
              ) : (
                <>
                  <Text style={{ textAlign: 'center', marginBottom: 10 }}>
                    Confirm PIN
                  </Text>
                  <CodeField
                    value={confirmPassword}
                    onChangeText={setConfirmPassword}
                    cellCount={4}
                    rootStyle={{ marginBottom: 20 }}
                    keyboardType="number-pad"
                    renderCell={({ index, symbol, isFocused }) => (
                      <View
                        key={index}
                        style={[
                          styles.pinCell,
                          isFocused && styles.pinCellFocused,
                        ]}
                      >
                        <Text style={{ fontSize: 24 }}>
                          {symbol || (isFocused ? <Cursor /> : null)}
                        </Text>
                      </View>
                    )}
                  />
                </>
              )}
            </>
          ) : (
            <>
              {step === 1 ? (
                <TextInput
                  placeholder="Enter Password"
                  secureTextEntry
                  style={styles.input}
                  value={password}
                  onChangeText={setPassword}
                />
              ) : (
                <TextInput
                  placeholder="Confirm Password"
                  secureTextEntry
                  style={styles.input}
                  value={confirmPassword}
                  onChangeText={setConfirmPassword}
                />
              )}
            </>
          )}
        </View>

        <View style={styles.btnCard}>
          <TouchableOpacity
            style={[styles.button, styles.removeButton]}
            onPress={() => {
              resetForm();
              navigation.goBack();
            }}
          >
            <Text style={styles.buttonText}>Bekor qilish</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.button} onPress={onContinue}>
            <Text style={styles.buttonText}>
              {step === 1 ? 'Davom etish' : 'Saqlash'}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  btnCard: {
    position: 'absolute',
    flexDirection: 'row',
    bottom: 5,
    width: '100%',
    justifyContent: 'center',
    gap: 10,
  },
  patternContainer: {
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  patternPoint: {
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: '#ddd',
    position: 'absolute',
  },
  patternPointActive: { backgroundColor: '#28A7E8' },
  pinCell: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    margin: 5,
  },
  pinCellFocused: { borderColor: '#28A7E8' },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 15,
    marginBottom: 15,
    fontSize: 16,
  },
  button: {
    backgroundColor: '#28A7E8',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
    width: '48%',
  },
  removeButton: { backgroundColor: '#ccc' },
  buttonText: { color: '#fff', fontSize: 16, fontWeight: 'bold' },
  lockCard: {
    height: '100%',
    justifyContent: 'center',
    width: '95%',
    margin: 'auto',
  },
  patternPointError: { backgroundColor: 'red' },
});

export default AddedLock;
