import React, { useState } from 'react';
import {
  Calendar,
  Clock,
  Video,
  ArrowRight,
  CalendarPlus,
  Share2,
  Check,
  Download,
} from 'lucide-react';
import { Container, Eyebrow } from './Ui';
import {
  CohortItem,
  UPCOMING_COHORTS,
  buildGoogleCalendarUrl,
  downloadIcsFile,
  formatCohortDate,
} from '../data/cohorts';
import { SUBJECTS, SubjectKey } from '../data/courses';

interface CohortScheduleProps {
  onNavigate: (path: string) => void;
  onOpenSyllabus?: (courseSlug?: string) => void;
  initialSubjectFilter?: SubjectKey | 'all';
  embeddedInCourse?: boolean;
}

export function CohortSchedule({
  onNavigate,
  onOpenSyllabus,
  initialSubjectFilter = 'all',
  embeddedInCourse = false,
}: CohortScheduleProps) {
  const [selectedSubject, setSelectedSubject] = useState<SubjectKey | 'all'>(initialSubjectFilter);
  const [calendarMenuOpen, setCalendarMenuOpen] = useState<string | null>(null);
  const [copiedLink, setCopiedLink] = useState<string | null>(null);

  const filteredCohorts = UPCOMING_COHORTS.filter((cohort) => {
    if (selectedSubject !== 'all' && cohort.subject !== selectedSubject) {
      return false;
    }
    return true;
  });

  const handleCopyLink = (cohort: CohortItem) => {
    const url = `${window.location.origin}/#/programmes/${cohort.courseSlug}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopiedLink(cohort.id);
      setTimeout(() => setCopiedLink(null), 2500);
    });
  };

  return (
    <section id="schedule" className="py-16 bg-background relative border-t border-border">
      <Container className="space-y-10">
        {/* Header Block */}
        <div className="max-w-2xl space-y-2">
          <Eyebrow>Cohort Schedules</Eyebrow>
          <h2 className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground">
            Upcoming live online intakes.
          </h2>
          <p className="text-sm sm:text-base text-muted-foreground leading-relaxed">
            All programmes are delivered 100% online through live Zoom and Google Meet masterclasses with dedicated WhatsApp cohort study groups. All times are East Africa Time (EAT, UTC+3).
          </p>
        </div>

        {/* Subject Filter Bar */}
        <div className="flex flex-wrap items-center gap-2 pb-4 border-b border-border">
          <button
            onClick={() => setSelectedSubject('all')}
            className={`px-4 py-2 rounded-full text-xs font-bold transition cursor-pointer ${
              selectedSubject === 'all'
                ? 'bg-primary text-primary-foreground shadow-xs'
                : 'bg-secondary/70 hover:bg-secondary text-foreground'
            }`}
          >
            All Intakes ({UPCOMING_COHORTS.length})
          </button>
          {(Object.keys(SUBJECTS) as SubjectKey[]).map((subjKey) => {
            const subj = SUBJECTS[subjKey];
            const count = UPCOMING_COHORTS.filter((c) => c.subject === subjKey).length;
            return (
              <button
                key={subjKey}
                onClick={() => setSelectedSubject(subjKey)}
                className={`px-4 py-2 rounded-full text-xs font-bold transition cursor-pointer flex items-center gap-1.5 ${
                  selectedSubject === subjKey
                    ? 'bg-primary text-primary-foreground shadow-xs'
                    : 'bg-secondary/70 hover:bg-secondary text-foreground'
                }`}
              >
                <span>{subj.short}</span>
                <span className="text-[10px] opacity-75">({count})</span>
              </button>
            );
          })}
        </div>

        {/* Cohort Cards Grid */}
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {filteredCohorts.map((cohort) => {
            const meta = SUBJECTS[cohort.subject];
            const isMenuOpen = calendarMenuOpen === cohort.id;

            return (
              <div
                key={cohort.id}
                className="bg-card rounded-3xl border border-border p-6 sm:p-7 flex flex-col justify-between shadow-xs hover:border-primary/40 transition-all space-y-5"
              >
                <div className="space-y-4">
                  {/* Status & Subject */}
                  <div className="flex items-center justify-between text-xs">
                    <span className={`font-bold px-2.5 py-0.5 rounded-full ${meta.bgSoft} ${meta.textColor}`}>
                      {cohort.provider}
                    </span>
                    <span className="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-teal-soft text-teal">
                      Admissions Open
                    </span>
                  </div>

                  {/* Course Title */}
                  <h3
                    onClick={() => onNavigate(`/programmes/${cohort.courseSlug}`)}
                    className="font-bold text-lg text-foreground hover:text-primary transition-colors cursor-pointer leading-snug"
                  >
                    {cohort.courseTitle}
                  </h3>

                  {/* Schedule Details */}
                  <div className="space-y-2 pt-2 text-xs text-muted-foreground border-t border-border/60">
                    <div className="flex items-center gap-2 text-foreground font-medium">
                      <Calendar className="w-4 h-4 text-teal shrink-0" />
                      <span>Starts {formatCohortDate(cohort.startDate)}</span>
                    </div>

                    <div className="flex items-center gap-2">
                      <Clock className="w-4 h-4 text-muted-foreground shrink-0" />
                      <span>{cohort.scheduleTime}</span>
                    </div>

                    <div className="flex items-center gap-2">
                      <Video className="w-4 h-4 text-muted-foreground shrink-0" />
                      <span>{cohort.duration} · Live Zoom / Meet & WhatsApp</span>
                    </div>
                  </div>
                </div>

                {/* Card Actions */}
                <div className="pt-4 border-t border-border/60 flex items-center justify-between gap-2">
                  <button
                    onClick={() => onNavigate(`/contact?mode=learner&course=${cohort.courseSlug}`)}
                    className="flex-1 px-4 py-2.5 rounded-full text-xs font-bold bg-primary text-primary-foreground hover:opacity-90 transition cursor-pointer flex items-center justify-center gap-1.5 shadow-2xs"
                  >
                    <span>Enquire for Cohort</span>
                    <ArrowRight className="w-3.5 h-3.5" />
                  </button>

                  {/* Calendar Add Dropdown */}
                  <div className="relative">
                    <button
                      onClick={() => setCalendarMenuOpen(isMenuOpen ? null : cohort.id)}
                      className="p-2.5 rounded-full border border-border bg-card hover:bg-secondary text-muted-foreground hover:text-foreground transition cursor-pointer"
                      title="Add to calendar"
                      aria-label="Add to calendar options"
                    >
                      <CalendarPlus className="w-4 h-4" />
                    </button>

                    {isMenuOpen && (
                      <div className="absolute right-0 bottom-full mb-2 w-48 rounded-2xl bg-card border border-border shadow-lg p-2 z-20 space-y-1 text-xs">
                        <a
                          href={buildGoogleCalendarUrl(cohort)}
                          target="_blank"
                          rel="noreferrer"
                          onClick={() => setCalendarMenuOpen(null)}
                          className="flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-secondary text-foreground cursor-pointer"
                        >
                          <Calendar className="w-3.5 h-3.5 text-teal" />
                          <span>Google Calendar</span>
                        </a>
                        <button
                          onClick={() => {
                            downloadIcsFile(cohort);
                            setCalendarMenuOpen(null);
                          }}
                          className="w-full flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-secondary text-foreground cursor-pointer text-left"
                        >
                          <Download className="w-3.5 h-3.5 text-primary" />
                          <span>Apple / Outlook (.ics)</span>
                        </button>
                      </div>
                    )}
                  </div>

                  {/* Share button */}
                  <button
                    onClick={() => handleCopyLink(cohort)}
                    className="p-2.5 rounded-full border border-border bg-card hover:bg-secondary text-muted-foreground hover:text-foreground transition cursor-pointer"
                    title="Copy track link"
                    aria-label="Copy track link"
                  >
                    {copiedLink === cohort.id ? (
                      <Check className="w-4 h-4 text-teal" />
                    ) : (
                      <Share2 className="w-4 h-4" />
                    )}
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Timetable Advisory Note */}
        <div className="p-4 rounded-2xl bg-secondary/70 border border-border text-xs text-muted-foreground leading-relaxed flex items-center justify-between flex-wrap gap-3">
          <p>
            Need a corporate cohort or alternative timetable for your team? We arrange private weekday afternoon or dedicated weekend masterclasses for organisations.
          </p>
          <button
            onClick={() => onNavigate('/organisations')}
            className="font-bold text-primary hover:underline cursor-pointer inline-flex items-center gap-1 shrink-0"
          >
            <span>Custom Team Schedules</span>
            <ArrowRight className="w-3.5 h-3.5" />
          </button>
        </div>
      </Container>
    </section>
  );
}
