/**
 * Advisory Service Detail Page
 * Full details of an advisory service with advisor profile, availability, and booking
 */

import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
  ArrowLeft,
  Star,
  CheckCircle,
  Calendar,
  Clock,
  MessageCircle,
  Award,
  Globe,
  Shield,
  Video,
  AlertCircle,
  Loader2,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { useMarketplaceStore } from '../../../stores/marketplaceStore';
import { ReviewCard } from '../components';
import type { ServiceType } from '../../../types/marketplace.types';

export default function AdvisoryDetail() {
  const { slug } = useParams<{ slug: string }>();
  const {
    currentAdvisory: advisory,
    reviews,
    totalReviews,
    availableSlots,
    availabilityTimezone,
    loadingDetail,
    loadingReviews,
    loadingAvailability,
    error,
    fetchAdvisoryBySlug,
    fetchReviews,
    fetchAdvisorAvailability,
    bookConsultation,
    markReviewHelpful,
    resetCurrentProduct,
  } = useMarketplaceStore();

  const [selectedService, setSelectedService] = useState<ServiceType | null>(null);
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [selectedSlot, setSelectedSlot] = useState<string | null>(null);
  const [notes, setNotes] = useState('');
  const [booking, setBooking] = useState(false);

  useEffect(() => {
    if (slug) {
      fetchAdvisoryBySlug(slug);
    }
    return () => {
      resetCurrentProduct();
    };
  }, [slug, fetchAdvisoryBySlug, resetCurrentProduct]);

  useEffect(() => {
    if (advisory) {
      fetchReviews(advisory.id, 'advisory', { page: 1, pageSize: 5, sortBy: 'helpful' });
      // Set default service
      if (advisory.serviceTypes.length > 0 && !selectedService) {
        setSelectedService(advisory.serviceTypes[0]);
      }
    }
  }, [advisory, fetchReviews, selectedService]);

  useEffect(() => {
    if (advisory && selectedDate) {
      const dateStr = selectedDate.toISOString().split('T')[0];
      fetchAdvisorAvailability(advisory.id, dateStr);
    }
  }, [advisory, selectedDate, fetchAdvisorAvailability]);

  const handleDateChange = (direction: 'prev' | 'next') => {
    const newDate = new Date(selectedDate);
    if (direction === 'next') {
      newDate.setDate(newDate.getDate() + 1);
    } else {
      newDate.setDate(newDate.getDate() - 1);
    }
    setSelectedDate(newDate);
    setSelectedSlot(null);
  };

  const handleBook = async () => {
    if (!advisory || !selectedService || !selectedSlot) return;
    setBooking(true);
    try {
      await bookConsultation(advisory.id, {
        serviceTypeId: selectedService.id,
        scheduledAt: `${selectedDate.toISOString().split('T')[0]}T${selectedSlot}:00.000Z`,
        notes: notes || undefined,
      });
      // Show success or redirect
    } catch (err) {
      console.error('Failed to book:', err);
    } finally {
      setBooking(false);
    }
  };

  if (loadingDetail) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  if (error || !advisory) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
        <h2 className="text-xl font-semibold text-white mb-2">Advisory Not Found</h2>
        <p className="text-gray-400 mb-4">{error || 'The requested advisory does not exist.'}</p>
        <Link
          to="/marketplace"
          className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg"
        >
          Back to Marketplace
        </Link>
      </div>
    );
  }

  const formatDate = (date: Date) => {
    return date.toLocaleDateString('en-US', {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
    });
  };

  const isToday = (date: Date) => {
    const today = new Date();
    return date.toDateString() === today.toDateString();
  };

  return (
    <div className="space-y-8">
      {/* Back link */}
      <Link
        to="/marketplace"
        className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        Back to Marketplace
      </Link>

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column - Advisor Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Advisor Header */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <div className="flex items-start gap-6">
              {/* Avatar */}
              <div className="relative flex-shrink-0">
                {advisory.advisor.avatarUrl ? (
                  <img
                    src={advisory.advisor.avatarUrl}
                    alt={advisory.advisor.name}
                    className="w-24 h-24 rounded-full object-cover"
                  />
                ) : (
                  <div className="w-24 h-24 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center text-white text-2xl font-bold">
                    {advisory.advisor.name.charAt(0)}
                  </div>
                )}
                {/* Online indicator */}
                {advisory.availability === 'available' && (
                  <div className="absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-green-500 border-4 border-gray-800" />
                )}
              </div>

              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 mb-2">
                  <h1 className="text-2xl font-bold text-white">{advisory.advisor.name}</h1>
                  {advisory.advisor.verified && (
                    <CheckCircle className="w-6 h-6 text-blue-400" />
                  )}
                </div>

                {advisory.advisor.title && (
                  <p className="text-lg text-gray-400 mb-2">{advisory.advisor.title}</p>
                )}

                {/* Quick Stats */}
                <div className="flex items-center gap-4 mb-4">
                  <div className="flex items-center gap-1">
                    <Star className="w-5 h-5 text-yellow-400 fill-yellow-400" />
                    <span className="text-white font-medium">{advisory.rating.toFixed(1)}</span>
                    <span className="text-gray-500">({advisory.totalReviews} reviews)</span>
                  </div>
                  <span className="text-gray-600">|</span>
                  <div className="flex items-center gap-1 text-gray-400">
                    <MessageCircle className="w-4 h-4" />
                    <span>{advisory.totalConsultations} consultations</span>
                  </div>
                </div>

                {/* Experience */}
                <p className="text-gray-300">{advisory.advisor.experience}</p>
              </div>
            </div>
          </div>

          {/* About */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <h2 className="text-lg font-semibold text-white mb-4">About</h2>
            <p className="text-gray-300 mb-6">{advisory.description}</p>

            {/* Credentials */}
            {advisory.advisor.credentials.length > 0 && (
              <div className="mb-6">
                <h3 className="text-sm font-medium text-gray-400 mb-3">Credentials</h3>
                <div className="flex flex-wrap gap-2">
                  {advisory.advisor.credentials.map((cred, idx) => (
                    <span
                      key={idx}
                      className="px-3 py-1.5 bg-blue-500/10 text-blue-400 rounded-lg text-sm flex items-center gap-2"
                    >
                      <Award className="w-4 h-4" />
                      {cred}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Specializations */}
            <div className="mb-6">
              <h3 className="text-sm font-medium text-gray-400 mb-3">Specializations</h3>
              <div className="flex flex-wrap gap-2">
                {advisory.specializations.map((spec, idx) => (
                  <span
                    key={idx}
                    className="px-3 py-1.5 bg-purple-500/10 text-purple-400 rounded-lg text-sm"
                  >
                    {spec}
                  </span>
                ))}
              </div>
            </div>

            {/* Languages */}
            <div>
              <h3 className="text-sm font-medium text-gray-400 mb-3">Languages</h3>
              <div className="flex flex-wrap gap-2">
                {advisory.languages.map((lang, idx) => (
                  <span
                    key={idx}
                    className="px-3 py-1.5 bg-gray-700 text-gray-300 rounded-lg text-sm flex items-center gap-2"
                  >
                    <Globe className="w-4 h-4" />
                    {lang}
                  </span>
                ))}
              </div>
            </div>
          </div>

          {/* Service Types */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <h2 className="text-lg font-semibold text-white mb-4">Services Offered</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {advisory.serviceTypes.map((service) => (
                <div
                  key={service.id}
                  className={`p-4 rounded-lg border-2 cursor-pointer transition-colors ${
                    selectedService?.id === service.id
                      ? 'border-purple-500 bg-purple-500/10'
                      : 'border-gray-700 hover:border-gray-600'
                  }`}
                  onClick={() => setSelectedService(service)}
                >
                  <div className="flex items-start justify-between mb-2">
                    <h3 className="font-medium text-white">{service.name}</h3>
                    <p className="text-lg font-bold text-white">${service.priceUsd}</p>
                  </div>
                  <p className="text-sm text-gray-400 mb-2">{service.description}</p>
                  <p className="text-sm text-gray-500 flex items-center gap-1">
                    <Clock className="w-4 h-4" />
                    {service.durationMinutes} minutes
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Reviews Section */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-white">
                Reviews ({totalReviews})
              </h2>
            </div>

            {loadingReviews ? (
              <div className="flex justify-center py-8">
                <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
              </div>
            ) : reviews.length > 0 ? (
              <div className="space-y-4">
                {reviews.map((review) => (
                  <ReviewCard
                    key={review.id}
                    review={review}
                    onMarkHelpful={markReviewHelpful}
                  />
                ))}
              </div>
            ) : (
              <p className="text-gray-400 text-center py-8">No reviews yet.</p>
            )}
          </div>
        </div>

        {/* Right Column - Booking */}
        <div className="space-y-6">
          {/* Booking Card */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 sticky top-6">
            <h2 className="text-lg font-semibold text-white mb-4">Book a Consultation</h2>

            {/* Selected Service */}
            {selectedService && (
              <div className="mb-4 p-3 bg-gray-900/50 rounded-lg">
                <p className="text-sm text-gray-400 mb-1">Selected Service</p>
                <p className="font-medium text-white">{selectedService.name}</p>
                <p className="text-sm text-gray-400">
                  {selectedService.durationMinutes} min - ${selectedService.priceUsd}
                </p>
              </div>
            )}

            {/* Date Picker */}
            <div className="mb-4">
              <div className="flex items-center justify-between mb-3">
                <button
                  onClick={() => handleDateChange('prev')}
                  disabled={isToday(selectedDate)}
                  className="p-2 text-gray-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="w-5 h-5" />
                </button>
                <div className="text-center">
                  <p className="font-medium text-white">{formatDate(selectedDate)}</p>
                  <p className="text-xs text-gray-500">{availabilityTimezone}</p>
                </div>
                <button
                  onClick={() => handleDateChange('next')}
                  className="p-2 text-gray-400 hover:text-white"
                >
                  <ChevronRight className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* Time Slots */}
            <div className="mb-4">
              <p className="text-sm text-gray-400 mb-3">Available Times</p>
              {loadingAvailability ? (
                <div className="flex justify-center py-4">
                  <Loader2 className="w-5 h-5 text-blue-500 animate-spin" />
                </div>
              ) : availableSlots.length > 0 ? (
                <div className="grid grid-cols-3 gap-2">
                  {availableSlots.map((slot) => (
                    <button
                      key={slot}
                      onClick={() => setSelectedSlot(slot)}
                      className={`py-2 px-3 rounded-lg text-sm font-medium transition-colors ${
                        selectedSlot === slot
                          ? 'bg-purple-600 text-white'
                          : 'bg-gray-900 text-gray-400 hover:text-white hover:bg-gray-700'
                      }`}
                    >
                      {slot}
                    </button>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500 text-center py-4">No slots available</p>
              )}
            </div>

            {/* Notes */}
            <div className="mb-6">
              <label className="block text-sm text-gray-400 mb-2">
                Notes (optional)
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="What would you like to discuss?"
                rows={3}
                className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-purple-500 focus:outline-none resize-none"
              />
            </div>

            {/* Book Button */}
            <button
              onClick={handleBook}
              disabled={booking || !selectedService || !selectedSlot}
              className="w-full py-3 bg-purple-600 hover:bg-purple-500 text-white font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {booking ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <>
                  <Calendar className="w-5 h-5" />
                  Book Consultation
                </>
              )}
            </button>

            {/* Price Summary */}
            {selectedService && (
              <div className="mt-4 pt-4 border-t border-gray-700">
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-400">Total</span>
                  <span className="font-bold text-white">${selectedService.priceUsd}</span>
                </div>
              </div>
            )}

            {/* Trust Signals */}
            <div className="mt-6 pt-6 border-t border-gray-700 space-y-3">
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <Video className="w-5 h-5 text-blue-400" />
                <span>Video call via Zoom/Meet</span>
              </div>
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <Shield className="w-5 h-5 text-green-400" />
                <span>Full refund if cancelled 24h before</span>
              </div>
              <div className="flex items-center gap-3 text-sm text-gray-400">
                <Clock className="w-5 h-5 text-purple-400" />
                <span>Responds in ~{advisory.responseTimeHours}h</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
