import React, { useState } from 'react';
import {
  Modal, View, Text, TouchableOpacity, ScrollView,
  TextInput, StyleSheet, Animated, KeyboardAvoidingView,
  Platform, Alert, SafeAreaView,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { COLORS, FONTS, FONT_SIZE, SPACING, RADIUS } from '../theme';

interface Props { isOpen: boolean; onClose: () => void; }

const AVAILABLE_DATES = [
  { label: 'Mon, Jun 29', value: '2026-06-29' },
  { label: 'Tue, Jun 30', value: '2026-06-30' },
  { label: 'Wed, Jul 1',  value: '2026-07-01' },
  { label: 'Thu, Jul 2',  value: '2026-07-02' },
  { label: 'Fri, Jul 3',  value: '2026-07-03' },
];
const AVAILABLE_TIMES = ['09:00 AM', '11:00 AM', '02:00 PM', '04:00 PM'];

const SESSION_TYPES = [
  {
    id:    'discovery',
    label: 'Free Discovery Call',
    meta:  '15 min • Phone or Video',
    price: 'FREE',
    desc:  'An initial confidential chat. Discuss your concerns, explore fit — zero obligation.',
  },
  {
    id:    'standard',
    label: 'Standard Session',
    meta:  '60 min • In-person or Online',
    price: '$100',
    desc:  'Full therapeutic session integrating hypnotherapy, EMDR, somatic breathwork, or ACT.',
  },
];

export default function BookingModal({ isOpen, onClose }: Props) {
  const [step, setStep] = useState(1);
  const [sessionType, setSessionType] = useState('discovery');
  const [selectedDate, setSelectedDate] = useState('');
  const [selectedTime, setSelectedTime] = useState('');
  const [name,  setName]  = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [notes, setNotes] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const reset = () => {
    setStep(1); setSessionType('discovery'); setSelectedDate('');
    setSelectedTime(''); setName(''); setEmail('');
    setPhone(''); setNotes(''); setIsSubmitting(false);
    onClose();
  };

  const handleNext = () => {
    if (step === 2 && (!selectedDate || !selectedTime)) {
      Alert.alert('Please select a date and time slot.');
      return;
    }
    setStep(s => s + 1);
  };

  const handleSubmit = () => {
    if (!name.trim() || !email.trim()) {
      Alert.alert('Please enter your name and email.');
      return;
    }
    setIsSubmitting(true);
    setTimeout(() => { setIsSubmitting(false); setStep(4); }, 1500);
  };

  const chosenSession = SESSION_TYPES.find(s => s.id === sessionType);

  return (
    <Modal visible={isOpen} animationType="slide" transparent onRequestClose={reset}>
      <KeyboardAvoidingView
        style={styles.overlay}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <View style={styles.sheet}>

          {/* Header */}
          <View style={styles.header}>
            <View>
              <Text style={styles.headerTitle}>Schedule Appointment</Text>
              <Text style={styles.headerSub}>YOUR WAVE Healing Practice</Text>
            </View>
            <TouchableOpacity onPress={reset} style={styles.closeBtn}>
              <Ionicons name="close" size={22} color={COLORS.slate400} />
            </TouchableOpacity>
          </View>

          {/* Step indicators */}
          {step < 4 && (
            <View style={styles.stepBar}>
              {['Format', 'Date & Time', 'Details'].map((label, i) => (
                <Text key={label} style={[styles.stepLabel, step === i + 1 && styles.stepLabelActive]}>
                  {i + 1}. {label}
                </Text>
              ))}
            </View>
          )}

          <ScrollView style={styles.body} showsVerticalScrollIndicator={false}>

            {/* STEP 1 — Session type */}
            {step === 1 && (
              <View style={styles.stepContent}>
                <Text style={styles.sectionLabel}>Select Session Format</Text>
                {SESSION_TYPES.map(s => (
                  <TouchableOpacity
                    key={s.id}
                    style={[styles.card, sessionType === s.id && styles.cardActive]}
                    onPress={() => setSessionType(s.id)}
                  >
                    <View style={styles.cardRow}>
                      <Text style={styles.cardTitle}>{s.label}</Text>
                      <View style={[styles.badge, sessionType === s.id ? styles.badgeDark : styles.badgeLight]}>
                        <Text style={[styles.badgeText, sessionType === s.id ? styles.badgeTextWhite : styles.badgeTextDark]}>
                          {s.price}
                        </Text>
                      </View>
                    </View>
                    <Text style={styles.cardMeta}>{s.meta}</Text>
                    <Text style={styles.cardDesc}>{s.desc}</Text>
                  </TouchableOpacity>
                ))}
                <TouchableOpacity style={styles.btnPrimary} onPress={handleNext}>
                  <Text style={styles.btnPrimaryText}>Next Step</Text>
                  <Ionicons name="chevron-forward" size={16} color={COLORS.white} />
                </TouchableOpacity>
              </View>
            )}

            {/* STEP 2 — Date & Time */}
            {step === 2 && (
              <View style={styles.stepContent}>
                <Text style={styles.sectionLabel}>Select Date</Text>
                <View style={styles.grid2}>
                  {AVAILABLE_DATES.map(d => (
                    <TouchableOpacity
                      key={d.value}
                      style={[styles.chipBtn, selectedDate === d.value && styles.chipBtnActive]}
                      onPress={() => setSelectedDate(d.value)}
                    >
                      <Text style={[styles.chipText, selectedDate === d.value && styles.chipTextActive]}>
                        {d.label}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>

                <Text style={[styles.sectionLabel, { marginTop: SPACING.lg }]}>Select Time Slot</Text>
                <View style={styles.grid4}>
                  {AVAILABLE_TIMES.map(t => (
                    <TouchableOpacity
                      key={t}
                      style={[styles.chipBtn, selectedTime === t && styles.chipBtnActive]}
                      onPress={() => setSelectedTime(t)}
                    >
                      <Text style={[styles.chipText, selectedTime === t && styles.chipTextActive]}>{t}</Text>
                    </TouchableOpacity>
                  ))}
                </View>

                <View style={styles.rowBtns}>
                  <TouchableOpacity style={styles.btnSecondary} onPress={() => setStep(1)}>
                    <Text style={styles.btnSecondaryText}>Back</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.btnPrimary} onPress={handleNext}>
                    <Text style={styles.btnPrimaryText}>Continue</Text>
                    <Ionicons name="chevron-forward" size={16} color={COLORS.white} />
                  </TouchableOpacity>
                </View>
              </View>
            )}

            {/* STEP 3 — Details */}
            {step === 3 && (
              <View style={styles.stepContent}>
                <Text style={styles.sectionLabel}>Your Contact Details</Text>

                <View style={styles.summaryBox}>
                  <Text style={styles.summaryLabel}>SELECTION SUMMARY</Text>
                  <Text style={styles.summaryValue}>{chosenSession?.label}</Text>
                  <Text style={styles.summaryValue}>{selectedDate} at {selectedTime}</Text>
                </View>

                {[
                  { label: 'Full Name *', value: name, setter: setName, keyboard: 'default' as const, placeholder: 'e.g. Jean Bosco' },
                  { label: 'Email Address *', value: email, setter: setEmail, keyboard: 'email-address' as const, placeholder: 'e.g. bosco@gmail.com' },
                  { label: 'Phone Number', value: phone, setter: setPhone, keyboard: 'phone-pad' as const, placeholder: 'e.g. +250 790 000 000' },
                ].map(f => (
                  <View key={f.label} style={styles.fieldGroup}>
                    <Text style={styles.fieldLabel}>{f.label}</Text>
                    <TextInput
                      style={styles.input}
                      value={f.value}
                      onChangeText={f.setter}
                      keyboardType={f.keyboard}
                      placeholder={f.placeholder}
                      placeholderTextColor={COLORS.slate400}
                      autoCapitalize="none"
                    />
                  </View>
                ))}

                <View style={styles.fieldGroup}>
                  <Text style={styles.fieldLabel}>Short Note / Concerns (Optional)</Text>
                  <TextInput
                    style={[styles.input, styles.textArea]}
                    value={notes}
                    onChangeText={setNotes}
                    multiline
                    numberOfLines={4}
                    placeholder="e.g. I am looking for EMDR support for stress..."
                    placeholderTextColor={COLORS.slate400}
                    textAlignVertical="top"
                  />
                </View>

                <View style={styles.rowBtns}>
                  <TouchableOpacity style={styles.btnSecondary} onPress={() => setStep(2)}>
                    <Text style={styles.btnSecondaryText}>Back</Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    style={[styles.btnPrimary, isSubmitting && styles.btnDisabled]}
                    onPress={handleSubmit}
                    disabled={isSubmitting}
                  >
                    <Ionicons name="send" size={14} color={COLORS.white} />
                    <Text style={styles.btnPrimaryText}>
                      {isSubmitting ? 'Confirming...' : 'Confirm Booking'}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
            )}

            {/* STEP 4 — Success */}
            {step === 4 && (
              <View style={[styles.stepContent, styles.successView]}>
                <View style={styles.successIcon}>
                  <Ionicons name="checkmark" size={32} color={COLORS.slate900} />
                </View>
                <Text style={styles.successTitle}>Appointment Confirmed!</Text>
                <Text style={styles.successDesc}>
                  Your appointment has been successfully scheduled. An email confirmation will be sent to you shortly.
                </Text>
                <View style={styles.summaryBox}>
                  <Text style={styles.summaryLabel}>BOOKING SUMMARY</Text>
                  <Text style={styles.summaryValue}>{chosenSession?.label}</Text>
                  <Text style={styles.summaryValue}>{selectedDate} at {selectedTime}</Text>
                  <Text style={styles.summaryValue}>Practitioner: Manuel Haeussler</Text>
                </View>
                <TouchableOpacity style={[styles.btnPrimary, { alignSelf: 'stretch' }]} onPress={reset}>
                  <Text style={styles.btnPrimaryText}>Done</Text>
                </TouchableOpacity>
              </View>
            )}
          </ScrollView>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1, backgroundColor: 'rgba(15,23,42,0.5)',
    justifyContent: 'flex-end',
  },
  sheet: {
    backgroundColor: COLORS.white,
    borderTopLeftRadius: 16, borderTopRightRadius: 16,
    maxHeight: '92%', overflow: 'hidden',
  },
  header: {
    backgroundColor: COLORS.slate900, paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md, flexDirection: 'row',
    justifyContent: 'space-between', alignItems: 'center',
  },
  headerTitle: {
    color: COLORS.white, fontFamily: FONTS.sans,
    fontWeight: '800', fontSize: FONT_SIZE.md, letterSpacing: 1,
    textTransform: 'uppercase',
  },
  headerSub: {
    color: COLORS.slate400, fontFamily: FONTS.sans,
    fontSize: FONT_SIZE.xxs, letterSpacing: 2, textTransform: 'uppercase', marginTop: 2,
  },
  closeBtn: { padding: SPACING.xs },
  stepBar: {
    flexDirection: 'row', justifyContent: 'space-around',
    backgroundColor: COLORS.slate50, paddingVertical: SPACING.sm,
    borderBottomWidth: 1, borderBottomColor: COLORS.slate200,
  },
  stepLabel: {
    fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs,
    color: COLORS.slate400, fontWeight: '700',
    textTransform: 'uppercase', letterSpacing: 1,
  },
  stepLabelActive: { color: COLORS.slate900 },
  body: { flex: 1 },
  stepContent: { padding: SPACING.lg, gap: SPACING.md },
  sectionLabel: {
    fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs,
    color: COLORS.slate900, fontWeight: '700',
    textTransform: 'uppercase', letterSpacing: 2,
  },
  card: {
    borderWidth: 2, borderColor: COLORS.slate200,
    padding: SPACING.md, gap: SPACING.xs,
  },
  cardActive: { borderColor: COLORS.slate900, backgroundColor: COLORS.slate50 },
  cardRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  cardTitle: {
    fontFamily: FONTS.sans, fontWeight: '700',
    fontSize: FONT_SIZE.sm, color: COLORS.slate900,
    textTransform: 'uppercase', letterSpacing: 1,
  },
  cardMeta: { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate500 },
  cardDesc: { fontFamily: FONTS.serif, fontSize: FONT_SIZE.xs, color: COLORS.slate500, lineHeight: 18 },
  badge: { paddingHorizontal: SPACING.sm, paddingVertical: 2 },
  badgeDark: { backgroundColor: COLORS.slate900 },
  badgeLight: { backgroundColor: COLORS.slate100 },
  badgeText: { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 1 },
  badgeTextWhite: { color: COLORS.white },
  badgeTextDark: { color: COLORS.slate700 },
  grid2: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.sm },
  grid4: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.sm },
  chipBtn: {
    borderWidth: 1, borderColor: COLORS.slate200,
    paddingHorizontal: SPACING.md, paddingVertical: SPACING.sm,
    backgroundColor: COLORS.slate50,
  },
  chipBtnActive: { backgroundColor: COLORS.slate900, borderColor: COLORS.slate900 },
  chipText: {
    fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs,
    fontWeight: '700', color: COLORS.slate800,
    textTransform: 'uppercase', letterSpacing: 1,
  },
  chipTextActive: { color: COLORS.white },
  rowBtns: {
    flexDirection: 'row', justifyContent: 'space-between',
    marginTop: SPACING.md, gap: SPACING.sm,
  },
  btnPrimary: {
    flex: 1, backgroundColor: COLORS.slate900,
    paddingVertical: SPACING.sm + 2, paddingHorizontal: SPACING.lg,
    flexDirection: 'row', alignItems: 'center',
    justifyContent: 'center', gap: SPACING.xs,
  },
  btnPrimaryText: {
    color: COLORS.white, fontFamily: FONTS.sans,
    fontWeight: '700', fontSize: FONT_SIZE.xxs,
    textTransform: 'uppercase', letterSpacing: 2,
  },
  btnSecondary: {
    flex: 0.5, backgroundColor: COLORS.slate100,
    paddingVertical: SPACING.sm + 2, paddingHorizontal: SPACING.md,
    alignItems: 'center', justifyContent: 'center',
  },
  btnSecondaryText: {
    color: COLORS.slate900, fontFamily: FONTS.sans,
    fontWeight: '700', fontSize: FONT_SIZE.xxs,
    textTransform: 'uppercase', letterSpacing: 2,
  },
  btnDisabled: { backgroundColor: COLORS.slate200 },
  fieldGroup: { gap: 4 },
  fieldLabel: {
    fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs,
    color: COLORS.slate400, fontWeight: '700',
    textTransform: 'uppercase', letterSpacing: 2,
  },
  input: {
    backgroundColor: COLORS.slate50, borderWidth: 1,
    borderColor: COLORS.slate200, paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.sm + 2, fontFamily: FONTS.sans,
    fontSize: FONT_SIZE.sm, color: COLORS.slate900,
  },
  textArea: { minHeight: 100, paddingTop: SPACING.sm },
  summaryBox: {
    backgroundColor: COLORS.slate50, borderWidth: 1,
    borderColor: COLORS.slate200, padding: SPACING.md, gap: 4,
  },
  summaryLabel: {
    fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs,
    color: COLORS.slate400, fontWeight: '700',
    textTransform: 'uppercase', letterSpacing: 2,
  },
  summaryValue: { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate700 },
  successView: { alignItems: 'center', paddingVertical: SPACING.xl },
  successIcon: {
    width: 64, height: 64, borderWidth: 1,
    borderColor: COLORS.slate200, backgroundColor: COLORS.slate50,
    alignItems: 'center', justifyContent: 'center', marginBottom: SPACING.md,
  },
  successTitle: {
    fontFamily: FONTS.sans, fontWeight: '800',
    fontSize: FONT_SIZE.md, color: COLORS.slate900,
    textTransform: 'uppercase', letterSpacing: 1,
  },
  successDesc: {
    fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm,
    color: COLORS.slate500, textAlign: 'center',
    lineHeight: 20, maxWidth: 300,
  },
});
