import { useEffect, useMemo, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Switch, Text, View } from 'react-native';
import { colors, radii, spacing } from '../../constants/theme';
import { buildTimeOptions, displayTime, type BusinessHours } from '../../utils/formValueHelpers';

const DAYS = [
  { key: 'monday', label: 'Monday' },
  { key: 'tuesday', label: 'Tuesday' },
  { key: 'wednesday', label: 'Wednesday' },
  { key: 'thursday', label: 'Thursday' },
  { key: 'friday', label: 'Friday' },
  { key: 'saturday', label: 'Saturday' },
  { key: 'sunday', label: 'Sunday' },
];

type Props = {
  label: string;
  value: BusinessHours;
  onChange: (value: BusinessHours) => void;
  readOnly?: boolean;
};

export function BusinessHoursField({ label, value, onChange, readOnly }: Props) {
  const timeOptions = useMemo(() => buildTimeOptions(), []);
  const [expandedDay, setExpandedDay] = useState<string | null>(null);
  const [expandedField, setExpandedField] = useState<'open' | 'close' | null>(null);

  const hours = value || {};

  const toggleDay = (day: string, enabled: boolean) => {
    const next = { ...hours };
    if (enabled) next[day] = next[day] || { open: '09:00', close: '17:00' };
    else delete next[day];
    onChange(next);
  };

  const updateDay = (day: string, field: 'open' | 'close', time: string) => {
    const next = { ...hours };
    const current = next[day] || { open: '09:00', close: '17:00' };
    next[day] = { ...current, [field]: time };
    onChange(next);
    setExpandedDay(null);
    setExpandedField(null);
  };

  return (
    <View style={styles.wrap}>
      <Text style={styles.label}>{label}</Text>
      {DAYS.map((day) => {
        const dayHours = hours[day.key];
        const isOpen = Boolean(dayHours?.open && dayHours?.close);
        const showPicker = expandedDay === day.key && expandedField;

        return (
          <View key={day.key} style={styles.dayCard}>
            <View style={styles.dayHeader}>
              <Text style={styles.dayLabel}>{day.label}</Text>
              <Switch
                value={isOpen}
                onValueChange={(enabled) => toggleDay(day.key, enabled)}
                disabled={readOnly}
                trackColor={{ true: colors.primary }}
              />
            </View>

            {isOpen ? (
              <View style={styles.timeRow}>
                <Pressable
                  style={styles.timeBtn}
                  disabled={readOnly}
                  onPress={() => {
                    if (expandedDay === day.key && expandedField === 'open') {
                      setExpandedDay(null);
                      setExpandedField(null);
                    } else {
                      setExpandedDay(day.key);
                      setExpandedField('open');
                    }
                  }}
                >
                  <Text style={styles.timeBtnLabel}>Open</Text>
                  <Text style={styles.timeBtnValue}>{displayTime(dayHours?.open || '09:00')}</Text>
                </Pressable>
                <Pressable
                  style={styles.timeBtn}
                  disabled={readOnly}
                  onPress={() => {
                    if (expandedDay === day.key && expandedField === 'close') {
                      setExpandedDay(null);
                      setExpandedField(null);
                    } else {
                      setExpandedDay(day.key);
                      setExpandedField('close');
                    }
                  }}
                >
                  <Text style={styles.timeBtnLabel}>Close</Text>
                  <Text style={styles.timeBtnValue}>{displayTime(dayHours?.close || '17:00')}</Text>
                </Pressable>
              </View>
            ) : (
              <Text style={styles.closedText}>Closed</Text>
            )}

            {showPicker && expandedField ? (
              <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.pickerScroll}>
                <View style={styles.pickerRow}>
                  {timeOptions.map((time) => {
                    const selected = dayHours?.[expandedField] === time;
                    return (
                      <Pressable
                        key={time}
                        style={[styles.timeChip, selected && styles.timeChipActive]}
                        onPress={() => updateDay(day.key, expandedField, time)}
                      >
                        <Text style={[styles.timeChipText, selected && styles.timeChipTextActive]}>
                          {displayTime(time)}
                        </Text>
                      </Pressable>
                    );
                  })}
                </View>
              </ScrollView>
            ) : null}
          </View>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { marginBottom: spacing.md },
  label: { fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: spacing.sm },
  dayCard: {
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: radii.md,
    borderWidth: 1,
    marginBottom: spacing.sm,
    padding: spacing.sm,
  },
  dayHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  dayLabel: { color: colors.text, fontSize: 15, fontWeight: '600' },
  timeRow: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.sm },
  timeBtn: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: radii.sm,
    borderWidth: 1,
    flex: 1,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
  },
  timeBtnLabel: { color: colors.textMuted, fontSize: 11, fontWeight: '600', marginBottom: 2 },
  timeBtnValue: { color: colors.text, fontSize: 14, fontWeight: '700' },
  closedText: { color: colors.textMuted, fontSize: 13, marginTop: spacing.xs },
  pickerScroll: { marginTop: spacing.sm, maxHeight: 44 },
  pickerRow: { flexDirection: 'row', gap: spacing.xs, paddingBottom: spacing.xs },
  timeChip: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: radii.pill,
    borderWidth: 1,
    paddingHorizontal: spacing.sm,
    paddingVertical: 6,
  },
  timeChipActive: {
    backgroundColor: colors.primaryLight,
    borderColor: colors.primary,
  },
  timeChipText: { color: colors.text, fontSize: 12, fontWeight: '500' },
  timeChipTextActive: { color: colors.primaryDark, fontWeight: '700' },
});
