import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Modal } from 'react-native';
import { DateTimePickerEvent } from '@react-native-community/datetimepicker';
import { useSettings } from '@/theme';

interface WebDateTimeInputProps {
  value: Date;
  mode: 'date' | 'time';
  isVisible: boolean;
  onChange: (event: DateTimePickerEvent, date?: Date) => void;
  onDismiss: () => void;
  testID?: string;
  is24Hour?: boolean;
}

function pad(n: number): string {
  return String(n).padStart(2, '0');
}

function dateInputValue(value: Date): string {
  return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
}

function timeInputValue(value: Date): string {
  return `${pad(value.getHours())}:${pad(value.getMinutes())}`;
}

export default function WebDateTimeInput({
  value,
  mode,
  isVisible,
  onChange,
  onDismiss,
  is24Hour,
}: WebDateTimeInputProps) {
  const { theme } = useSettings();
  const [inputValue, setInputValue] = useState(() => dateInputValue(value));
  const [prevValue, setPrevValue] = useState(value);

  if (value !== prevValue) {
    setPrevValue(value);
    setInputValue(dateInputValue(value));
  }

  const emit = (raw: string) => {
    if (!raw) return;
    let date: Date;
    if (mode === 'date') {
      date = new Date(`${raw}T00:00:00`);
    } else {
      const [hours, minutes] = raw.split(':').map(Number);
      date = new Date();
      date.setHours(hours, minutes, 0, 0);
    }
    const event: DateTimePickerEvent = {
      type: 'set',
      nativeEvent: { timestamp: date.getTime(), utcOffset: date.getTimezoneOffset() },
    };
    onChange(event, date);
  };

  const bgColor = theme.sheetBg;
  const textColor = theme.text;
  const borderColor = theme.borderStrong;
  const overlayColor = theme.overlay;
  const mutedColor = theme.textFaint;

  return (
    <Modal visible={isVisible} transparent animationType="fade" onRequestClose={onDismiss}>
      <View style={[styles.overlay, { backgroundColor: overlayColor }]}>
        <View style={[styles.sheet, { backgroundColor: bgColor }]}>
          <Text style={[styles.title, { color: textColor }]}>
            {mode === 'date' ? 'Choose Date' : 'Choose Time'}
          </Text>
          <View style={styles.inputWrapper}>
            {React.createElement('input', {
              type: mode,
              value: mode === 'date' ? inputValue : timeInputValue(value),
              onChange: (e: React.ChangeEvent<HTMLInputElement>) => {
                const raw = e.target.value;
                if (mode === 'date') {
                  setInputValue(raw);
                  emit(raw);
                } else {
                  emit(raw);
                }
              },
              autoFocus: true,
              style: {
                fontSize: 16,
                padding: 12,
                borderRadius: 10,
                border: `1px solid ${borderColor}`,
                outline: 'none',
                backgroundColor: theme.inputBg,
                color: textColor,
                fontFamily: 'inherit',
                marginVertical: 16,
                width: '100%',
                boxSizing: 'border-box',
              },
            })}
          </View>
          <View style={styles.actions}>
            <TouchableOpacity
              style={[styles.clearButton, { borderColor, backgroundColor: theme.inputBg }]}
              onPress={onDismiss}
              activeOpacity={0.7}
            >
              <Text style={[styles.clearButtonText, { color: mutedColor }]}>Clear</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.doneButton, { backgroundColor: theme.accent }]} onPress={onDismiss} activeOpacity={0.8}>
              <Text style={[styles.doneButtonText, { color: theme.accentText }]}>Done</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 24,
  },
  sheet: {
    width: '100%',
    maxWidth: 360,
    borderRadius: 16,
    padding: 20,
    alignItems: 'center',
  },
  title: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 8,
  },
  inputWrapper: {
    width: '100%',
  },
  actions: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    gap: 12,
    width: '100%',
  },
  clearButton: {
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 10,
    borderWidth: 1,
  },
  clearButtonText: {
    fontSize: 15,
    fontWeight: '500',
  },
  doneButton: {
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 10,
  },
  doneButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
});