import React, { useState } from 'react';
import { SERVICES_LIST, PRACTICE_INFO } from '../data/mockData';
import { X, Calendar, Clock, User, Phone, Mail, CheckCircle2, ShieldCheck, AlertCircle, FileText, Stethoscope } from 'lucide-react';

interface BookingModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialServiceId?: string;
}

export const BookingModal: React.FC<BookingModalProps> = ({
  isOpen,
  onClose,
  initialServiceId
}) => {
  const [step, setStep] = useState<'service' | 'datetime' | 'details' | 'success'>('service');
  
  const [selectedServiceId, setSelectedServiceId] = useState<string>(
    initialServiceId || SERVICES_LIST[0].id
  );
  const [selectedDoctor, setSelectedDoctor] = useState<string>("Dr. T. M. Matseke (Principal Physician)");
  
  // Generate next 10 dates for simple selection
  const today = new Date();
  const availableDates = Array.from({ length: 10 }, (_, i) => {
    const d = new Date(today);
    d.setDate(today.getDate() + i + 1);
    // Skip sundays
    if (d.getDay() === 0) d.setDate(d.getDate() + 1);
    return {
      dateStr: d.toISOString().split('T')[0],
      label: d.toLocaleDateString('en-ZA', { weekday: 'short', month: 'short', day: 'numeric' }),
      isSaturday: d.getDay() === 6
    };
  });

  const [selectedDate, setSelectedDate] = useState<string>(availableDates[0].dateStr);
  const [selectedTime, setSelectedTime] = useState<string>("09:30 AM");
  
  // Form details
  const [patientName, setPatientName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [medicalAidName, setMedicalAidName] = useState("Discovery Health");
  const [medicalAidNumber, setMedicalAidNumber] = useState("");
  const [isFirstVisit, setIsFirstVisit] = useState(true);
  const [notes, setNotes] = useState("");
  const [referenceCode, setReferenceCode] = useState("");

  if (!isOpen) return null;

  const selectedService = SERVICES_LIST.find(s => s.id === selectedServiceId) || SERVICES_LIST[0];

  const timeSlots = [
    "08:30 AM", "09:15 AM", "10:00 AM", "10:45 AM", 
    "11:30 AM", "02:00 PM", "02:45 PM", "03:30 PM", "04:15 PM"
  ];

  const handleCompleteBooking = (e: React.FormEvent) => {
    e.preventDefault();
    if (!patientName || !phone) return;
    const code = "DMS-" + Math.floor(100000 + Math.random() * 900000);
    setReferenceCode(code);
    setStep('success');
  };

  const resetAndClose = () => {
    setStep('service');
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200">
      <div className="bg-white rounded-2xl max-w-2xl w-full overflow-hidden shadow-2xl border border-slate-100 transition-all">
        
        {/* Modal Header */}
        <div className="bg-gradient-to-r from-primary to-secondary p-6 text-white relative flex items-center justify-between">
          <div>
            <div className="flex items-center space-x-2 text-xs font-semibold uppercase tracking-wider text-medical-accent/90 mb-1">
              <Stethoscope className="w-4 h-4" />
              <span>Online Patient Scheduler</span>
            </div>
            <h2 className="text-xl sm:text-2xl font-bold">
              {step === 'success' ? 'Appointment Confirmed!' : 'Book Your Consultation'}
            </h2>
          </div>
          <button
            onClick={resetAndClose}
            className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white transition-colors"
            aria-label="Close modal"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Progress Bar */}
        {step !== 'success' && (
          <div className="bg-slate-100 px-6 py-3 border-b border-slate-200 flex items-center justify-between text-xs font-semibold text-slate-500">
            <span className={step === 'service' ? 'text-primary font-bold' : 'text-slate-600'}>
              1. Select Service
            </span>
            <span className="text-slate-300">→</span>
            <span className={step === 'datetime' ? 'text-primary font-bold' : 'text-slate-600'}>
              2. Date & Time
            </span>
            <span className="text-slate-300">→</span>
            <span className={step === 'details' ? 'text-primary font-bold' : 'text-slate-600'}>
              3. Patient Details
            </span>
          </div>
        )}

        {/* Modal Body */}
        <div className="p-6 sm:p-8 max-h-[75vh] overflow-y-auto">
          
          {/* STEP 1: SERVICE & DOCTOR */}
          {step === 'service' && (
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-semibold text-slate-800 mb-2">
                  Choose Medical Service Required:
                </label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {SERVICES_LIST.map((srv) => {
                    const isSelected = selectedServiceId === srv.id;
                    return (
                      <div
                        key={srv.id}
                        onClick={() => setSelectedServiceId(srv.id)}
                        className={`p-4 rounded-xl border-2 cursor-pointer transition-all ${
                          isSelected
                            ? 'border-primary bg-primary/5 shadow-sm'
                            : 'border-slate-200 hover:border-primary/40 bg-white'
                        }`}
                      >
                        <div className="font-bold text-sm text-slate-900 mb-1 flex items-center justify-between">
                          <span>{srv.title}</span>
                          {isSelected && <span className="w-2 h-2 rounded-full bg-primary" />}
                        </div>
                        <p className="text-xs text-slate-500 line-clamp-2">{srv.shortDescription}</p>
                        <div className="mt-2 text-[11px] font-semibold text-secondary flex items-center justify-between">
                          <span>⏱ {srv.duration}</span>
                          <span>{srv.priceRange.split('/')[0]}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-800 mb-2">
                  Select Healthcare Practitioner:
                </label>
                <select
                  value={selectedDoctor}
                  onChange={(e) => setSelectedDoctor(e.target.value)}
                  className="w-full p-3.5 rounded-xl border border-slate-300 font-medium text-sm text-slate-800 focus:ring-2 focus:ring-primary focus:outline-none bg-slate-50"
                >
                  <option value="Dr. T. M. Matseke (Principal Physician)">Dr. T. M. Matseke — Principal Physician & Founder</option>
                  <option value="Associate Practitioner (Next Available Slot)">Associate Medical Practitioner — First Available</option>
                </select>
              </div>

              <div className="bg-medical-accent/60 p-4 rounded-xl border border-primary/20 flex items-start space-x-3 text-xs text-slate-700">
                <ShieldCheck className="w-5 h-5 text-primary flex-shrink-0 mt-0.5" />
                <div>
                  <strong className="text-slate-900 block mb-0.5">Direct Medical Aid Billing Available</strong>
                  We submit claims directly to Discovery, Bonitas, Momentum, GEMS, Medihelp, Bestmed, and Bankmed at standard contracted rates.
                </div>
              </div>

              <div className="flex justify-end pt-2">
                <button
                  onClick={() => setStep('datetime')}
                  className="bg-primary hover:bg-primary-dark text-white px-6 py-3 rounded-xl font-semibold text-sm shadow-md transition-all flex items-center space-x-2"
                >
                  <span>Next: Choose Date & Time</span>
                  <span>→</span>
                </button>
              </div>
            </div>
          )}

          {/* STEP 2: DATE & TIME */}
          {step === 'datetime' && (
            <div className="space-y-6">
              <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 flex items-center justify-between text-xs">
                <div>
                  <span className="text-slate-500 block">Selected Service:</span>
                  <span className="font-bold text-slate-800 text-sm">{selectedService.title}</span>
                </div>
                <button
                  onClick={() => setStep('service')}
                  className="text-primary hover:underline font-semibold"
                >
                  Change
                </button>
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-800 mb-2 flex items-center space-x-1.5">
                  <Calendar className="w-4 h-4 text-primary" />
                  <span>Select Consultation Date:</span>
                </label>
                <div className="grid grid-cols-2 sm:grid-cols-5 gap-2.5">
                  {availableDates.map((d) => {
                    const isSel = selectedDate === d.dateStr;
                    return (
                      <button
                        key={d.dateStr}
                        onClick={() => setSelectedDate(d.dateStr)}
                        className={`p-3 rounded-xl border text-center transition-all ${
                          isSel
                            ? 'bg-primary text-white border-primary shadow-sm font-bold'
                            : 'bg-white border-slate-200 hover:border-primary/40 text-slate-700'
                        }`}
                      >
                        <span className="block text-xs uppercase tracking-wider opacity-80">
                          {d.label.split(',')[0]}
                        </span>
                        <span className="block text-sm font-bold mt-0.5">
                          {d.label.split(',')[1]}
                        </span>
                        {d.isSaturday && (
                          <span className="inline-block text-[10px] bg-amber-100 text-amber-800 px-1.5 py-0.5 rounded mt-1 font-semibold">
                            Morning Only
                          </span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-800 mb-2 flex items-center space-x-1.5">
                  <Clock className="w-4 h-4 text-secondary" />
                  <span>Select Preferred Time Slot:</span>
                </label>
                <div className="grid grid-cols-3 sm:grid-cols-4 gap-2.5">
                  {timeSlots.map((time) => {
                    const isSel = selectedTime === time;
                    return (
                      <button
                        key={time}
                        onClick={() => setSelectedTime(time)}
                        className={`py-2.5 px-3 rounded-xl border text-sm font-semibold transition-all ${
                          isSel
                            ? 'bg-secondary text-white border-secondary shadow-sm'
                            : 'bg-white border-slate-200 hover:border-secondary/40 text-slate-700'
                        }`}
                      >
                        {time}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="flex justify-between pt-4 border-t border-slate-100">
                <button
                  onClick={() => setStep('service')}
                  className="px-5 py-2.5 rounded-xl border border-slate-300 font-semibold text-slate-600 hover:bg-slate-50 text-sm"
                >
                  ← Back
                </button>
                <button
                  onClick={() => setStep('details')}
                  className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-xl font-semibold text-sm shadow-md transition-all flex items-center space-x-2"
                >
                  <span>Next: Patient Details</span>
                  <span>→</span>
                </button>
              </div>
            </div>
          )}

          {/* STEP 3: PATIENT DETAILS */}
          {step === 'details' && (
            <form onSubmit={handleCompleteBooking} className="space-y-4">
              <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 flex flex-wrap items-center justify-between gap-2 text-xs">
                <div>
                  <span className="text-slate-500 block">Appointment Summary:</span>
                  <span className="font-bold text-slate-800 text-sm">{selectedService.title}</span>
                  <span className="block text-secondary font-semibold">📅 {selectedDate} at {selectedTime}</span>
                </div>
                <button
                  type="button"
                  onClick={() => setStep('datetime')}
                  className="text-primary hover:underline font-semibold"
                >
                  Change Slot
                </button>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Full Name & Surname *
                  </label>
                  <div className="relative">
                    <User className="w-4 h-4 text-slate-400 absolute left-3.5 top-3.5" />
                    <input
                      type="text"
                      required
                      value={patientName}
                      onChange={(e) => setPatientName(e.target.value)}
                      placeholder="e.g. Sipho Mokoena"
                      className="w-full pl-10 pr-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Mobile Number (SMS / WhatsApp) *
                  </label>
                  <div className="relative">
                    <Phone className="w-4 h-4 text-slate-400 absolute left-3.5 top-3.5" />
                    <input
                      type="tel"
                      required
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      placeholder="e.g. 082 555 0192"
                      className="w-full pl-10 pr-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                    />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Email Address (For Calendar Invite)
                  </label>
                  <div className="relative">
                    <Mail className="w-4 h-4 text-slate-400 absolute left-3.5 top-3.5" />
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      placeholder="sipho@example.co.za"
                      className="w-full pl-10 pr-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Patient Type
                  </label>
                  <select
                    value={isFirstVisit ? "new" : "existing"}
                    onChange={(e) => setIsFirstVisit(e.target.value === "new")}
                    className="w-full px-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none bg-white"
                  >
                    <option value="new">New Patient (First Visit to Dr. Matseke)</option>
                    <option value="existing">Existing Patient / Follow-Up</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Medical Aid Provider
                  </label>
                  <select
                    value={medicalAidName}
                    onChange={(e) => setMedicalAidName(e.target.value)}
                    className="w-full px-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none bg-white"
                  >
                    <option value="Discovery Health">Discovery Health</option>
                    <option value="Bonitas Medical Fund">Bonitas Medical Fund</option>
                    <option value="Government Employees (GEMS)">Government Employees (GEMS)</option>
                    <option value="Momentum Health">Momentum Health</option>
                    <option value="Bestmed Medical Scheme">Bestmed Medical Scheme</option>
                    <option value="Medihelp Medical Scheme">Medihelp Medical Scheme</option>
                    <option value="Bankmed">Bankmed</option>
                    <option value="Private Cash / Card Payment">Private Cash / Card Payment</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                    Medical Aid Membership Number
                  </label>
                  <input
                    type="text"
                    value={medicalAidNumber}
                    onChange={(e) => setMedicalAidNumber(e.target.value)}
                    placeholder="Optional (if claiming via scheme)"
                    className="w-full px-4 py-3 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1">
                  Brief Reason for Visit / Symptoms
                </label>
                <textarea
                  rows={2}
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="e.g. Routine blood pressure check, persistent throat cough, or executive checkup..."
                  className="w-full px-4 py-2.5 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-primary focus:outline-none resize-none"
                />
              </div>

              <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 flex items-start space-x-2 text-xs text-amber-900">
                <AlertCircle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
                <span>
                  <strong>Important:</strong> If you are experiencing chest pains, shortness of breath, or severe bleeding, please proceed immediately to an emergency hospital unit.
                </span>
              </div>

              <div className="flex justify-between pt-4 border-t border-slate-100">
                <button
                  type="button"
                  onClick={() => setStep('datetime')}
                  className="px-5 py-2.5 rounded-xl border border-slate-300 font-semibold text-slate-600 hover:bg-slate-50 text-sm"
                >
                  ← Back
                </button>
                <button
                  type="submit"
                  className="bg-gradient-to-r from-primary to-secondary hover:opacity-90 text-white px-8 py-3 rounded-xl font-bold text-sm shadow-lg transition-all flex items-center space-x-2"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  <span>Confirm Appointment</span>
                </button>
              </div>
            </form>
          )}

          {/* STEP 4: SUCCESS CONFIRMATION */}
          {step === 'success' && (
            <div className="text-center py-6 space-y-6 animate-in zoom-in-95 duration-300">
              <div className="w-16 h-16 bg-secondary/10 rounded-full flex items-center justify-center mx-auto text-secondary shadow-inner">
                <CheckCircle2 className="w-10 h-10 stroke-[2.5]" />
              </div>

              <div>
                <span className="inline-block px-3 py-1 bg-medical-accent text-primary rounded-full text-xs font-bold uppercase tracking-wider mb-2">
                  Reference: #{referenceCode}
                </span>
                <h3 className="text-2xl font-bold text-slate-900">Appointment Successfully Scheduled!</h3>
                <p className="text-sm text-slate-600 max-w-md mx-auto mt-2">
                  Thank you, <strong className="text-slate-900">{patientName}</strong>. We have reserved your appointment slot with Dr. Matseke Surgery. A confirmation SMS has been sent to <strong className="text-slate-900">{phone}</strong>.
                </p>
              </div>

              <div className="bg-slate-50 border border-slate-200 rounded-2xl p-5 text-left max-w-md mx-auto space-y-3 text-sm">
                <div className="flex justify-between border-b border-slate-200/60 pb-2">
                  <span className="text-slate-500 font-medium">Service:</span>
                  <span className="font-bold text-slate-800">{selectedService.title}</span>
                </div>
                <div className="flex justify-between border-b border-slate-200/60 pb-2">
                  <span className="text-slate-500 font-medium">Date & Time:</span>
                  <span className="font-bold text-secondary">📅 {selectedDate} @ {selectedTime}</span>
                </div>
                <div className="flex justify-between border-b border-slate-200/60 pb-2">
                  <span className="text-slate-500 font-medium">Practitioner:</span>
                  <span className="font-medium text-slate-800">{selectedDoctor.split('—')[0]}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500 font-medium">Location:</span>
                  <span className="font-medium text-slate-800 text-right text-xs sm:text-sm max-w-[200px] sm:max-w-xs">{PRACTICE_INFO.address}</span>
                </div>
              </div>

              {selectedService.preparation && (
                <div className="bg-blue-50 border border-blue-200 rounded-xl p-3.5 text-xs text-blue-900 text-left max-w-md mx-auto flex items-start space-x-2">
                  <FileText className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                  <div>
                    <strong>Preparation Reminder:</strong> {selectedService.preparation}
                  </div>
                </div>
              )}

              <div className="pt-2 flex flex-col sm:flex-row gap-3 justify-center">
                <button
                  onClick={() => alert(`Simulated downloading calendar invite (${referenceCode}.ics) for ${selectedDate} at ${selectedTime}.`)}
                  className="px-5 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-semibold text-sm transition-all flex items-center justify-center space-x-2"
                >
                  <Calendar className="w-4 h-4 text-primary" />
                  <span>Add to Apple / Google Calendar</span>
                </button>
                <button
                  onClick={resetAndClose}
                  className="px-8 py-2.5 rounded-xl bg-primary hover:bg-primary-dark text-white font-bold text-sm shadow-md transition-all"
                >
                  Done & Close
                </button>
              </div>
            </div>
          )}

        </div>

        {/* Modal Footer */}
        {step !== 'success' && (
          <div className="bg-slate-50 px-6 py-3 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
            <span className="flex items-center space-x-1">
              <ShieldCheck className="w-4 h-4 text-secondary" />
              <span>HPCSA Confidentiality Guarantee</span>
            </span>
            <span>Need telephone help? Call <strong>{PRACTICE_INFO.phone}</strong></span>
          </div>
        )}

      </div>
    </div>
  );
};
