'use client';

import { useEffect, useState } from 'react';
import { Plus, X, Save, CalendarDays } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { BookLessonData, LessonBooking, LocalizedString } from '@/types';
import Button from '@/components/ui/Button';
import Input, { Textarea } from '@/components/ui/Input';
import ImageUploader from '@/components/ui/ImageUploader';
import { PageSpinner } from '@/components/ui/Spinner';
import LanguageTabs, { useLanguageTabs, Lang } from '@/components/ui/LanguageTabs';
import Section from '@/components/ui/Section';

const emptyLS = (): LocalizedString => ({ en: '', zh: '' });

function asLS(val: unknown): LocalizedString {
  if (val && typeof val === 'object' && 'en' in val) return val as LocalizedString;
  if (typeof val === 'string') return { en: val, zh: '' };
  return emptyLS();
}

const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

type Tab = 'editor' | 'bookings';

export default function BookLessonsEditorPage() {
  const { activeLang, setActiveLang } = useLanguageTabs();
  const [activeTab, setActiveTab] = useState<Tab>('editor');
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  // Hero
  const [heroTitle, setHeroTitle] = useState<LocalizedString>(emptyLS());
  const [heroSubtitle, setHeroSubtitle] = useState<LocalizedString>(emptyLS());
  const [heroDescription, setHeroDescription] = useState<LocalizedString>(emptyLS());
  const [heroImage, setHeroImage] = useState('');
  const [heroCtaText, setHeroCtaText] = useState<LocalizedString>(emptyLS());
  const [heroCtaLink, setHeroCtaLink] = useState('');

  // Booking section
  const [bookingTitle, setBookingTitle] = useState<LocalizedString>(emptyLS());
  const [bookingSubtitle, setBookingSubtitle] = useState<LocalizedString>(emptyLS());
  const [bookingDescription, setBookingDescription] = useState<LocalizedString>(emptyLS());

  // Schedule config
  const [availableDays, setAvailableDays] = useState<number[]>([1, 2, 3, 4]);
  const [timeSlots, setTimeSlots] = useState<Array<{ startTime: string; endTime: string }>>([
    { startTime: '15:00', endTime: '16:00' },
    { startTime: '16:00', endTime: '17:00' },
  ]);
  const [maxCapacity, setMaxCapacity] = useState(1);

  // Terms
  const [terms, setTerms] = useState<LocalizedString[]>([]);

  // Bookings
  const [bookings, setBookings] = useState<LessonBooking[]>([]);
  const [bookingsPage, setBookingsPage] = useState(1);
  const [bookingsTotal, setBookingsTotal] = useState(0);
  const [statusFilter, setStatusFilter] = useState('all');

  const updateLS = (setter: React.Dispatch<React.SetStateAction<LocalizedString>>, lang: Lang, value: string) => {
    setter((prev) => ({ ...prev, [lang]: value }));
  };

  const loadFromData = (data: BookLessonData) => {
    setHeroTitle(asLS(data.heroTitle));
    setHeroSubtitle(asLS(data.heroSubtitle));
    setHeroDescription(asLS(data.heroDescription));
    setHeroImage(data.heroImage ?? '');
    setHeroCtaText(asLS(data.heroCtaText));
    setHeroCtaLink(data.heroCtaLink ?? '');
    setBookingTitle(asLS(data.bookingTitle));
    setBookingSubtitle(asLS(data.bookingSubtitle));
    setBookingDescription(asLS(data.bookingDescription));
    setAvailableDays(data.availableDays ?? [1, 2, 3, 4]);
    setTimeSlots(
      (data.timeSlots ?? []).length > 0
        ? data.timeSlots
        : [{ startTime: '15:00', endTime: '16:00' }, { startTime: '16:00', endTime: '17:00' }]
    );
    setMaxCapacity(data.maxCapacityPerSlot ?? 1);
    setTerms((data.termsAndConditions ?? []).map((t) => asLS(t)));
  };

  useEffect(() => {
    api
      .getBookLesson()
      .then(loadFromData)
      .catch(() => toast.error('Failed to load Book Lessons data'))
      .finally(() => setIsLoading(false));
  }, []);

  const loadBookings = async (p = 1, status = statusFilter) => {
    try {
      const data = await api.getBookLessonBookings({ page: p, limit: 15, status });
      setBookings(data.bookings ?? []);
      setBookingsTotal(data.pagination?.total ?? 0);
      setBookingsPage(p);
    } catch {
      toast.error('Failed to load bookings');
    }
  };

  useEffect(() => {
    if (activeTab === 'bookings') loadBookings();
  }, [activeTab]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const data: Partial<BookLessonData> = {
        heroTitle,
        heroSubtitle,
        heroDescription,
        heroImage: heroImage || undefined,
        heroCtaText,
        heroCtaLink: heroCtaLink || undefined,
        bookingTitle,
        bookingSubtitle,
        bookingDescription,
        availableDays,
        timeSlots,
        maxCapacityPerSlot: maxCapacity,
        termsAndConditions: terms,
      };
      const updated = await api.updateBookLesson(data);
      loadFromData(updated);
      toast.success('Book Lessons page saved');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setIsSaving(false);
    }
  };

  const toggleDay = (day: number) => {
    setAvailableDays((prev) =>
      prev.includes(day) ? prev.filter((d) => d !== day) : [...prev, day].sort()
    );
  };

  const addTimeSlot = () => setTimeSlots([...timeSlots, { startTime: '', endTime: '' }]);
  const removeTimeSlot = (idx: number) => setTimeSlots(timeSlots.filter((_, i) => i !== idx));
  const updateSlot = (idx: number, field: 'startTime' | 'endTime', value: string) =>
    setTimeSlots(timeSlots.map((s, i) => (i === idx ? { ...s, [field]: value } : s)));

  const addTerm = () => setTerms([...terms, emptyLS()]);
  const removeTerm = (idx: number) => setTerms(terms.filter((_, i) => i !== idx));
  const updateTerm = (idx: number, lang: Lang, value: string) =>
    setTerms(terms.map((t, i) => (i === idx ? { ...t, [lang]: value } : t)));

  const handleStatusChange = async (id: string, newStatus: string) => {
    try {
      await api.updateBookingStatus(id, { status: newStatus });
      setBookings((prev) =>
        prev.map((b) => (b._id === id ? { ...b, status: newStatus as LessonBooking['status'] } : b))
      );
      toast.success('Status updated');
    } catch {
      toast.error('Failed to update status');
    }
  };

  if (isLoading) return <PageSpinner />;

  const statusBadge = (status: string) => {
    const styles: Record<string, string> = {
      pending: 'bg-yellow-100 text-yellow-800',
      confirmed: 'bg-green-100 text-green-800',
      cancelled: 'bg-red-100 text-red-800',
    };
    return (
      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${styles[status] ?? 'bg-gray-100 text-gray-800'}`}>
        {status}
      </span>
    );
  };

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Book Lessons</h1>
        {activeTab === 'editor' && (
          <Button type="submit" form="book-lessons-form" isLoading={isSaving}>
            <Save size={16} />
            Save changes
          </Button>
        )}
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200">
        <button
          type="button"
          onClick={() => setActiveTab('editor')}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'editor'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          Page Editor
        </button>
        <button
          type="button"
          onClick={() => setActiveTab('bookings')}
          className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
            activeTab === 'bookings'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          }`}
        >
          <span className="flex items-center gap-1.5">
            <CalendarDays size={14} />
            Bookings
            {bookingsTotal > 0 && (
              <span className="bg-blue-100 text-blue-700 text-xs px-1.5 py-0.5 rounded-full">{bookingsTotal}</span>
            )}
          </span>
        </button>
      </div>

      {activeTab === 'editor' ? (
        <form id="book-lessons-form" onSubmit={handleSave} className="space-y-5">
          <LanguageTabs activeLang={activeLang} onChange={setActiveLang} />

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            <Section title="Hero Section">
              <Input
                label={`Title (${activeLang.toUpperCase()})`}
                value={heroTitle[activeLang]}
                onChange={(e) => updateLS(setHeroTitle, activeLang, e.target.value)}
                required
              />
              <Input
                label={`Subtitle (${activeLang.toUpperCase()})`}
                value={heroSubtitle[activeLang]}
                onChange={(e) => updateLS(setHeroSubtitle, activeLang, e.target.value)}
              />
              <Textarea
                label={`Description (${activeLang.toUpperCase()})`}
                value={heroDescription[activeLang]}
                onChange={(e) => updateLS(setHeroDescription, activeLang, e.target.value)}
                rows={4}
              />
              <ImageUploader label="Hero background image" value={heroImage} onChange={setHeroImage} />
              <div className="grid grid-cols-2 gap-3">
                <Input
                  label={`CTA button text (${activeLang.toUpperCase()})`}
                  value={heroCtaText[activeLang]}
                  onChange={(e) => updateLS(setHeroCtaText, activeLang, e.target.value)}
                />
                <Input
                  label="CTA link"
                  value={heroCtaLink}
                  onChange={(e) => setHeroCtaLink(e.target.value)}
                  placeholder="https://..."
                />
              </div>
            </Section>

            <Section title="Booking Section">
              <Input
                label={`Title (${activeLang.toUpperCase()})`}
                value={bookingTitle[activeLang]}
                onChange={(e) => updateLS(setBookingTitle, activeLang, e.target.value)}
              />
              <Input
                label={`Subtitle (${activeLang.toUpperCase()})`}
                value={bookingSubtitle[activeLang]}
                onChange={(e) => updateLS(setBookingSubtitle, activeLang, e.target.value)}
              />
              <Textarea
                label={`Description (${activeLang.toUpperCase()})`}
                value={bookingDescription[activeLang]}
                onChange={(e) => updateLS(setBookingDescription, activeLang, e.target.value)}
                rows={2}
              />
            </Section>
          </div>

          {/* Schedule Configuration */}
          <Section title="Schedule Configuration">
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Available Days</label>
                <div className="flex flex-wrap gap-2">
                  {DAY_LABELS.map((label, idx) => (
                    <button
                      key={idx}
                      type="button"
                      onClick={() => toggleDay(idx)}
                      className={`px-3 py-1.5 text-sm rounded-lg border transition-colors ${
                        availableDays.includes(idx)
                          ? 'bg-blue-600 text-white border-blue-600'
                          : 'bg-white text-gray-600 border-gray-300 hover:border-blue-400'
                      }`}
                    >
                      {label}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Time Slots</label>
                <div className="space-y-2">
                  {timeSlots.map((slot, idx) => (
                    <div key={idx} className="flex items-center gap-2">
                      <input
                        type="time"
                        value={slot.startTime}
                        onChange={(e) => updateSlot(idx, 'startTime', e.target.value)}
                        className="px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <span className="text-gray-400">to</span>
                      <input
                        type="time"
                        value={slot.endTime}
                        onChange={(e) => updateSlot(idx, 'endTime', e.target.value)}
                        className="px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => removeTimeSlot(idx)}
                        className="text-gray-400 hover:text-red-500"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  ))}
                </div>
                <Button type="button" variant="secondary" size="sm" onClick={addTimeSlot} className="mt-2">
                  <Plus size={14} />
                  Add time slot
                </Button>
              </div>

              <div className="max-w-xs">
                <Input
                  type="number"
                  label="Max bookings per slot"
                  value={maxCapacity.toString()}
                  onChange={(e) => setMaxCapacity(Math.max(1, parseInt(e.target.value) || 1))}
                  min={1}
                />
              </div>
            </div>
          </Section>

          {/* Terms & Conditions */}
          <Section title="Terms & Conditions">
            <div className="space-y-3">
              {terms.map((term, idx) => (
                <div key={idx} className="flex gap-3 items-start">
                  <span className="text-sm text-gray-400 mt-2 min-w-[1.5rem] text-right">{idx + 1}.</span>
                  <div className="flex-1">
                    <textarea
                      value={term[activeLang]}
                      onChange={(e) => updateTerm(idx, activeLang, e.target.value)}
                      rows={2}
                      placeholder={`Term ${idx + 1} (${activeLang.toUpperCase()})`}
                      className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                    />
                  </div>
                  <button
                    type="button"
                    onClick={() => removeTerm(idx)}
                    className="mt-2 text-gray-400 hover:text-red-500"
                  >
                    <X size={16} />
                  </button>
                </div>
              ))}
            </div>
            <Button type="button" variant="secondary" size="sm" onClick={addTerm}>
              <Plus size={14} />
              Add term
            </Button>
          </Section>

          <div className="flex justify-end">
            <Button type="submit" isLoading={isSaving} size="lg">
              <Save size={16} />
              Save changes
            </Button>
          </div>
        </form>
      ) : (
        /* Bookings tab */
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
            <h2 className="text-sm font-semibold text-gray-700">Lesson Bookings ({bookingsTotal})</h2>
            <select
              value={statusFilter}
              onChange={(e) => {
                setStatusFilter(e.target.value);
                loadBookings(1, e.target.value);
              }}
              className="text-sm border border-gray-300 rounded-lg px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">All statuses</option>
              <option value="pending">Pending</option>
              <option value="confirmed">Confirmed</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
          {bookings.length === 0 ? (
            <div className="py-12 text-center text-gray-400 text-sm">No bookings yet.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-100 bg-gray-50/50">
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Date</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Time</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Name</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Email</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Phone</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Golf ID</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Status</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {bookings.map((bk) => (
                    <tr key={bk._id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-gray-900 whitespace-nowrap">
                        {new Date(bk.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                      </td>
                      <td className="px-4 py-3 text-gray-600 whitespace-nowrap">{bk.timeSlot}</td>
                      <td className="px-4 py-3 text-gray-900 whitespace-nowrap">{bk.firstName} {bk.lastName}</td>
                      <td className="px-4 py-3 text-gray-600">
                        <a href={`mailto:${bk.email}`} className="text-blue-600 hover:underline">{bk.email}</a>
                      </td>
                      <td className="px-4 py-3 text-gray-600 whitespace-nowrap">{bk.phone}</td>
                      <td className="px-4 py-3 text-gray-600">{bk.golfId || '—'}</td>
                      <td className="px-4 py-3">{statusBadge(bk.status)}</td>
                      <td className="px-4 py-3">
                        <select
                          value={bk.status}
                          onChange={(e) => handleStatusChange(bk._id, e.target.value)}
                          className="text-xs border border-gray-300 rounded px-1.5 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
                        >
                          <option value="pending">Pending</option>
                          <option value="confirmed">Confirmed</option>
                          <option value="cancelled">Cancelled</option>
                        </select>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
          {bookingsTotal > 15 && (
            <div className="px-4 py-3 border-t border-gray-100 flex items-center justify-center gap-2">
              <button
                type="button"
                disabled={bookingsPage <= 1}
                onClick={() => loadBookings(bookingsPage - 1)}
                className="px-3 py-1 text-sm border border-gray-300 rounded-lg disabled:opacity-50 hover:bg-gray-50"
              >
                Previous
              </button>
              <span className="text-sm text-gray-500">Page {bookingsPage}</span>
              <button
                type="button"
                disabled={bookingsPage * 15 >= bookingsTotal}
                onClick={() => loadBookings(bookingsPage + 1)}
                className="px-3 py-1 text-sm border border-gray-300 rounded-lg disabled:opacity-50 hover:bg-gray-50"
              >
                Next
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
