import React, { useState } from 'react';
import { PageType, ServiceItem } from '../../types';
import { SERVICES_LIST, FAQ_LIST, PRACTICE_INFO } from '../../data/mockData';
import { IconRenderer } from '../IconRenderer';
import { Calendar, ArrowRight, Clock, ShieldCheck, ChevronDown, CheckCircle2, HelpCircle, Phone, Search, Sparkles } from 'lucide-react';

interface ServicesPageProps {
  onNavigate: (page: PageType) => void;
  onOpenBooking: (serviceId?: string) => void;
  onSelectService: (service: ServiceItem) => void;
  onOpenContact: () => void;
}

export const ServicesPage: React.FC<ServicesPageProps> = ({
  onNavigate,
  onOpenBooking,
  onSelectService,
  onOpenContact
}) => {
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [openFaqId, setOpenFaqId] = useState<string | null>(FAQ_LIST[0].id);

  const categories = [
    { id: 'all', label: 'All Services (10)' },
    { id: 'general', label: 'General & Family' },
    { id: 'chronic', label: 'Chronic Management' },
    { id: 'preventative', label: 'Preventative & Screenings' },
    { id: 'specialized', label: "Women's & Men's Health" },
    { id: 'procedures', label: 'Minor Procedures' },
  ];

  const filteredServices = SERVICES_LIST.filter(srv => {
    const matchesCategory = selectedCategory === 'all' || srv.category === selectedCategory;
    const matchesSearch = srv.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          srv.shortDescription.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCategory && matchesSearch;
  });

  const patientJourneySteps = [
    {
      step: "01",
      title: "Book Appointment",
      desc: "Schedule online via our 60-second booking tool or call reception.",
      icon: "Calendar"
    },
    {
      step: "02",
      title: "Consultation",
      desc: "Unhurried, thorough physical examination and clinical discussion with Dr. Matseke.",
      icon: "Stethoscope"
    },
    {
      step: "03",
      title: "Diagnosis",
      desc: "Accurate diagnostic screening using on-site testing or pathcare laboratory coordination.",
      icon: "Activity"
    },
    {
      step: "04",
      title: "Treatment Plan",
      desc: "Tailored prescriptions, lifestyle advice, and direct electronic medical aid submission.",
      icon: "FileText"
    },
    {
      step: "05",
      title: "Follow-Up Care",
      desc: "Scheduled review sessions to monitor healing progress and titration of chronic dosages.",
      icon: "RefreshCw"
    }
  ];

  const toggleFaq = (id: string) => {
    setOpenFaqId(openFaqId === id ? null : id);
  };

  return (
    <div className="space-y-16 sm:space-y-24 pb-16">
      
      {/* HERO SECTION */}
      <section className="relative bg-slate-900 text-white overflow-hidden">
        <div className="absolute inset-0 z-0 opacity-25">
          <img
            src="https://images.unsplash.com/photo-1579684385127-1ef15d508118?auto=format&fit=crop&w=1600&q=80"
            alt="Medical equipment and clinical diagnostics"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-slate-900 via-slate-900/90 to-transparent" />
        </div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-24 relative z-10">
          <div className="max-w-3xl space-y-4">
            <span className="inline-flex items-center space-x-2 px-3.5 py-1 bg-[#E8F4FF] text-[#0A6EB4] text-xs font-bold rounded-full uppercase tracking-widest">
              <Sparkles className="w-4 h-4" />
              <span>Comprehensive Healthcare</span>
            </span>
            <h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold tracking-tight text-white leading-tight">
              Our Medical <span className="text-[#0A6EB4]">Services</span>
            </h1>
            <p className="text-lg sm:text-xl text-slate-300 font-normal leading-relaxed">
              Providing comprehensive, primary healthcare services for individuals and families at our surgery. Explore our clinical offerings below.
            </p>
          </div>
        </div>
      </section>

      {/* FILTER & SEARCH BAR */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-8 relative z-20">
        <div className="bg-white p-4 sm:p-6 rounded-2xl shadow-lg border border-slate-200/80 space-y-4">
          <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
            
            {/* Search Input */}
            <div className="relative w-full md:w-80">
              <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-3.5" />
              <input
                type="text"
                placeholder="Search medical services..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-slate-300 text-sm focus:ring-2 focus:ring-[#0A6EB4] focus:outline-none bg-[#F7F9FC]"
              />
            </div>

            {/* Direct medical aid badge */}
            <div className="flex items-center space-x-2 text-xs font-semibold text-slate-600 bg-[#E8F4FF]/70 px-4 py-2 rounded-xl border border-[#0A6EB4]/20">
              <ShieldCheck className="w-4 h-4 text-[#0A6EB4] flex-shrink-0" />
              <span>We submit claims directly to all major South African Medical Aids</span>
            </div>
          </div>

          {/* Category Tabs */}
          <div className="flex items-center gap-2 overflow-x-auto pb-2 sm:pb-0 pt-2 border-t border-slate-100 no-scrollbar">
            {categories.map((cat) => {
              const isActive = selectedCategory === cat.id;
              return (
                <button
                  key={cat.id}
                  onClick={() => setSelectedCategory(cat.id)}
                  className={`px-4 py-2 rounded-full text-xs font-bold transition-all whitespace-nowrap ${
                    isActive
                      ? 'bg-[#0A6EB4] text-white shadow-sm'
                      : 'bg-[#F7F9FC] text-slate-600 hover:bg-slate-200/80 hover:text-slate-900'
                  }`}
                >
                  {cat.label}
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {/* SERVICES GRID */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {filteredServices.length === 0 ? (
          <div className="text-center py-16 bg-[#F7F9FC] rounded-3xl border border-slate-200 p-8 space-y-4">
            <HelpCircle className="w-12 h-12 text-slate-400 mx-auto" />
            <h3 className="text-lg font-bold text-slate-800">No services found matching "{searchQuery}"</h3>
            <p className="text-sm text-slate-500">Try searching for general terms like "consultation", "diabetes", or "certificate", or select "All Services".</p>
            <button
              onClick={() => { setSelectedCategory('all'); setSearchQuery(''); }}
              className="px-5 py-2 rounded-xl bg-[#0A6EB4] text-white font-bold text-xs"
            >
              Reset Filters
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
            {filteredServices.map((srv) => {
              const isRedAccent = srv.iconName === 'HeartPulse' || srv.id === 'womens-health' || srv.id === 'minor-procedures';
              return (
                <div
                  key={srv.id}
                  className={`bg-white rounded-3xl p-6 sm:p-8 border shadow-sm hover:shadow-md transition-all duration-300 group flex flex-col justify-between ${
                    isRedAccent ? 'border-slate-200 hover:border-[#E63946]' : 'border-slate-200 hover:border-[#2FA8A1]'
                  }`}
                >
                  <div>
                    <div className="flex items-center justify-between mb-6">
                      <div className={`w-14 h-14 rounded-2xl border flex items-center justify-center transition-colors duration-300 shadow-xs ${
                        isRedAccent
                          ? 'bg-[#FFF0F1] border-[#E63946]/20 text-[#E63946] group-hover:bg-[#E63946] group-hover:text-white'
                          : 'bg-[#F7F9FC] border-slate-100 text-[#0A6EB4] group-hover:bg-[#0A6EB4] group-hover:text-white'
                      }`}>
                        <IconRenderer name={srv.iconName} className="w-7 h-7 stroke-[2]" />
                      </div>
                      <span className={`text-xs font-bold uppercase tracking-wider px-3 py-1 rounded-full ${
                        isRedAccent ? 'bg-[#FFF0F1] text-[#E63946]' : 'bg-[#E8F4FF] text-[#0A6EB4]'
                      }`}>
                        ⏱ {srv.duration}
                      </span>
                    </div>

                    <h3 className={`text-xl font-extrabold text-slate-900 mb-3 transition-colors ${
                      isRedAccent ? 'group-hover:text-[#E63946]' : 'group-hover:text-[#0A6EB4]'
                    }`}>
                      {srv.title}
                    </h3>
                    
                    <p className="text-sm text-slate-600 leading-relaxed mb-6">
                      {srv.fullDescription}
                    </p>

                    <div className="space-y-2 mb-6">
                      <span className="text-xs font-bold text-slate-500 uppercase tracking-wider block">Key Highlights:</span>
                      {srv.includes.slice(0, 3).map((inc, i) => (
                        <div key={i} className="flex items-start space-x-2 text-xs text-slate-700">
                          <CheckCircle2 className={`w-3.5 h-3.5 flex-shrink-0 mt-0.5 ${isRedAccent ? 'text-[#E63946]' : 'text-[#2FA8A1]'}`} />
                          <span className="line-clamp-1">{inc}</span>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="pt-6 border-t border-slate-100 flex items-center justify-between gap-3">
                    <div>
                      <span className="text-[10px] text-slate-400 font-semibold uppercase block">Tariff / Fee</span>
                      <span className="text-xs font-bold text-slate-800">{srv.priceRange.split('/')[0]}</span>
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => onSelectService(srv)}
                        className="px-3.5 py-2 rounded-xl bg-[#F7F9FC] hover:bg-slate-200 text-slate-700 font-bold text-xs transition-colors"
                      >
                        Details
                      </button>
                      <button
                        onClick={() => onOpenBooking(srv.id)}
                        className={`px-4 py-2 rounded-xl text-white font-bold text-xs shadow-sm transition-all flex items-center space-x-1 ${
                          isRedAccent ? 'bg-[#E63946] hover:bg-[#C92A37]' : 'bg-[#0A6EB4] hover:bg-[#085891]'
                        }`}
                      >
                        <span>Book</span>
                        <ArrowRight className="w-3 h-3" />
                      </button>
                    </div>
                  </div>

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

      {/* PROCESS SECTION: THE PATIENT JOURNEY */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="bg-[#F7F9FC] rounded-3xl p-8 sm:p-14 border border-slate-200/80 shadow-xs">
          <div className="text-center max-w-3xl mx-auto mb-12 space-y-3">
            <span className="inline-block px-3 py-1 bg-[#E8F4FF] text-[#0A6EB4] text-xs font-bold rounded-full uppercase tracking-widest">
              Step-by-Step Care
            </span>
            <h2 className="text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight">
              The Patient Journey
            </h2>
            <p className="text-slate-600 text-base sm:text-lg">
              We design every step of your consultation to be smooth, informative, and centered around your recovery and comfort.
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-5 gap-6 relative">
            {patientJourneySteps.map((step, idx) => (
              <div
                key={idx}
                className="bg-white p-6 rounded-2xl border border-slate-200 shadow-xs relative flex flex-col items-center text-center group hover:border-[#2FA8A1] transition-all"
              >
                <span className="text-xs font-black text-slate-300 absolute top-4 right-4">{step.step}</span>
                <div className="w-12 h-12 rounded-xl bg-[#E8F4FF] text-[#0A6EB4] flex items-center justify-center mb-4 group-hover:bg-[#0A6EB4] group-hover:text-white transition-colors">
                  <IconRenderer name={step.icon} className="w-6 h-6 stroke-[2]" />
                </div>
                <h3 className="text-base font-bold text-slate-900 mb-1">{step.title}</h3>
                <p className="text-xs text-slate-500 leading-relaxed">{step.desc}</p>
                
                {idx < patientJourneySteps.length - 1 && (
                  <div className="hidden md:block absolute -right-3 top-1/2 transform -translate-y-1/2 z-10 text-slate-300">
                    →
                  </div>
                )}
                {idx < patientJourneySteps.length - 1 && (
                  <div className="md:hidden text-center my-1 text-slate-300 font-bold">
                    ↓
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ SECTION */}
      <section className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center max-w-2xl mx-auto mb-10 space-y-2">
          <span className="inline-block px-3 py-1 bg-[#E8F4FF] text-[#0A6EB4] text-xs font-bold rounded-full uppercase tracking-widest">
            Got Questions?
          </span>
          <h2 className="text-3xl font-extrabold text-slate-900">
            Frequently Asked Questions
          </h2>
          <p className="text-slate-600 text-sm sm:text-base">
            Everything you need to know about appointments, medical aids, billing, and preparing for your visit.
          </p>
        </div>

        <div className="space-y-3">
          {FAQ_LIST.map((faq) => {
            const isOpen = openFaqId === faq.id;
            return (
              <div
                key={faq.id}
                className={`border rounded-2xl transition-all overflow-hidden ${
                  isOpen
                    ? 'bg-white border-[#0A6EB4] shadow-md'
                    : 'bg-white border-slate-200 hover:border-slate-300'
                }`}
              >
                <button
                  onClick={() => toggleFaq(faq.id)}
                  className="w-full p-5 sm:p-6 text-left flex items-center justify-between font-bold text-base text-slate-900 focus:outline-none"
                >
                  <span className="pr-4">{faq.question}</span>
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-transform ${isOpen ? 'bg-[#E8F4FF] text-[#0A6EB4] rotate-180' : 'bg-slate-100 text-slate-500'}`}>
                    <ChevronDown className="w-5 h-5" />
                  </div>
                </button>
                
                {isOpen && (
                  <div className="px-5 sm:px-6 pb-6 pt-1 text-sm sm:text-base text-slate-600 leading-relaxed border-t border-slate-100/80">
                    {faq.answer}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        <div className="mt-8 text-center bg-[#F7F9FC] p-6 rounded-2xl border border-slate-200">
          <p className="text-sm text-slate-700 font-medium">
            Have a question not listed here? Our reception team is happy to assist. Call us at{' '}
            <a href={`tel:${PRACTICE_INFO.phone.replace(/\s+/g, '')}`} className="font-bold text-[#0A6EB4] underline">
              {PRACTICE_INFO.phone}
            </a>
          </p>
        </div>
      </section>

      {/* FINAL CTA */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="bg-gradient-to-r from-[#0A6EB4] via-[#0A6EB4] to-[#2FA8A1] rounded-3xl p-8 sm:p-14 text-white shadow-xl text-center space-y-6 relative overflow-hidden">
          
          <div className="relative z-10 max-w-2xl mx-auto space-y-4">
            <span className="inline-block px-3.5 py-1 bg-white/20 backdrop-blur-md text-white text-xs font-bold rounded-full uppercase tracking-widest border border-white/30">
              Personalized Treatment
            </span>
            <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
              Need Medical Assistance?
            </h2>
            <p className="text-blue-100 text-base sm:text-lg leading-relaxed">
              Take the first step toward better health today. Schedule your consultation online or get in touch with our friendly surgery reception staff.
            </p>

            <div className="pt-4 flex flex-wrap justify-center gap-4">
              <button
                onClick={() => onOpenBooking()}
                className="bg-white text-[#0A6EB4] hover:bg-slate-100 px-8 py-4 rounded-full font-extrabold text-base shadow-lg transition-all flex items-center space-x-2 active:scale-95"
              >
                <Calendar className="w-5 h-5 text-[#2FA8A1]" />
                <span>Book Now</span>
              </button>
              
              <button
                onClick={onOpenContact}
                className="bg-black/20 hover:bg-black/30 backdrop-blur-md text-white border border-white/30 px-8 py-4 rounded-full font-bold text-base transition-all flex items-center space-x-2"
              >
                <Phone className="w-5 h-5" />
                <span>Contact Us</span>
              </button>
            </div>
          </div>
        </div>
      </section>

    </div>
  );
};
