'use client'

import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Search,
  Star,
  MapPin,
  Clock,
  Filter,
  X,
  Loader2,
  AlertCircle,
  GraduationCap,
  SlidersHorizontal,
  Users,
  Eye,
  CalendarPlus,
  Map,
} from 'lucide-react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { BRAND } from '@/lib/constants'

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface Tutor {
  id: string
  userId: string
  bio: string | null
  subjects: string[]
  hourlyRate: number | null
  rating: number
  totalSessions: number
  province: string | null
  city: string | null
  serviceType: string
  qualifications: string[]
  experience: string | null
  user: {
    id: string
    firstName: string | null
    lastName: string | null
    email: string
    profilePic: string | null
    province: string | null
    city: string | null
  }
}

/* ------------------------------------------------------------------ */
/* Constants                                                           */
/* ------------------------------------------------------------------ */

const PROVINCES = ['All Provinces', ...BRAND.provinces]
const SUBJECTS = ['All Subjects', ...BRAND.saSubjects]
const SERVICE_TYPES = ['All Types', 'Online', 'In-Person', 'Both']

const SORT_OPTIONS = [
  { value: 'rating', label: 'Highest Rated' },
  { value: 'price_asc', label: 'Price: Low to High' },
  { value: 'price_desc', label: 'Price: High to Low' },
  { value: 'sessions', label: 'Most Sessions' },
]

/* ------------------------------------------------------------------ */
/* Helper: render stars                                                */
/* ------------------------------------------------------------------ */

function RatingStars({ rating }: { rating: number }) {
  const stars = Math.round(rating * 2) / 2
  return (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((i) => (
        <Star
          key={i}
          className={`h-3.5 w-3.5 ${
            i <= stars
              ? 'text-yellow-400 fill-yellow-400'
              : i - 0.5 <= stars
                ? 'text-yellow-400 fill-yellow-400/50'
                : 'text-gray-300'
          }`}
        />
      ))}
      <span className="ml-1 text-xs font-medium text-gray-600">{rating.toFixed(1)}</span>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Main Page                                                           */
/* ------------------------------------------------------------------ */

export default function TutorsPage() {
  const [tutors, setTutors] = useState<Tutor[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [subject, setSubject] = useState('All Subjects')
  const [province, setProvince] = useState('All Provinces')
  const [city, setCity] = useState('')
  const [serviceType, setServiceType] = useState('All Types')
  const [minRating, setMinRating] = useState('0')
  const [priceMin, setPriceMin] = useState('')
  const [priceMax, setPriceMax] = useState('')
  const [sort, setSort] = useState('rating')
  const [showFilters, setShowFilters] = useState(false)
  const [bookDialog, setBookDialog] = useState<Tutor | null>(null)
  const [bookSubject, setBookSubject] = useState('')
  const [bookDate, setBookDate] = useState('')
  const [bookNotes, setBookNotes] = useState('')
  const [bookingLoading, setBookingLoading] = useState(false)

  const fetchTutors = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams()
      if (subject !== 'All Subjects') params.set('subject', subject)
      if (province !== 'All Provinces') params.set('province', province)
      if (city) params.set('city', city)
      if (serviceType !== 'All Types') params.set('serviceType', serviceType.toLowerCase())
      if (parseFloat(minRating) > 0) params.set('minRating', minRating)
      if (priceMin) params.set('priceMin', priceMin)
      if (priceMax) params.set('priceMax', priceMax)
      if (sort) params.set('sort', sort)

      const res = await fetch(`/api/tutors?${params.toString()}`)
      if (!res.ok) throw new Error('Failed to fetch tutors')
      const data = await res.json()
      setTutors(data.tutors || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred')
    } finally {
      setLoading(false)
    }
  }, [subject, province, city, serviceType, minRating, priceMin, priceMax, sort])

  useEffect(() => {
    fetchTutors()
  }, [fetchTutors])

  const filteredTutors = tutors.filter((t) => {
    if (!search) return true
    const q = search.toLowerCase()
    return (
      t.user.firstName?.toLowerCase().includes(q) ||
      t.user.lastName?.toLowerCase().includes(q) ||
      t.bio?.toLowerCase().includes(q) ||
      t.subjects.some((s) => s.toLowerCase().includes(q))
    )
  })

  const hasActiveFilters =
    subject !== 'All Subjects' ||
    province !== 'All Provinces' ||
    city !== '' ||
    serviceType !== 'All Types' ||
    parseFloat(minRating) > 0 ||
    priceMin !== '' ||
    priceMax !== ''

  const activeFilterCount = [
    subject !== 'All Subjects',
    province !== 'All Provinces',
    city !== '',
    serviceType !== 'All Types',
    parseFloat(minRating) > 0,
    priceMin !== '',
    priceMax !== '',
  ].filter(Boolean).length

  const handleBook = async () => {
    if (!bookDialog || !bookSubject || !bookDate) return
    setBookingLoading(true)
    try {
      const res = await fetch(`/api/tutors/${bookDialog.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          learnerId: 'demo-student',
          subject: bookSubject,
          dateTime: bookDate,
          notes: bookNotes,
        }),
      })
      if (!res.ok) throw new Error('Booking failed')
      setBookDialog(null)
      setBookSubject('')
      setBookDate('')
      setBookNotes('')
    } catch {
      alert('Failed to book session. Please try again.')
    } finally {
      setBookingLoading(false)
    }
  }

  const clearFilters = () => {
    setSubject('All Subjects')
    setProvince('All Provinces')
    setCity('')
    setServiceType('All Types')
    setMinRating('0')
    setPriceMin('')
    setPriceMax('')
  }

  const getInitials = (tutor: Tutor) => {
    const first = tutor.user.firstName || ''
    const last = tutor.user.lastName || ''
    return (first[0] || '') + (last[0] || '')
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center"
              style={{ background: BRAND.colors.primaryGradient }}
            >
              <Search className="w-4 h-4 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900">Find Tutors</h1>
          </div>
          <p className="text-sm text-gray-500">
            Connect with qualified tutors across South Africa
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Select value={sort} onValueChange={setSort}>
            <SelectTrigger className="w-[180px] rounded-xl">
              <SlidersHorizontal className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
              <SelectValue placeholder="Sort by" />
            </SelectTrigger>
            <SelectContent>
              {SORT_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Search and Filter Bar */}
      <div className="space-y-3 mb-6">
        <div className="flex gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by name, subject, or keyword..."
              className="pl-10 rounded-xl"
            />
          </div>
          <Button
            variant="outline"
            onClick={() => setShowFilters(!showFilters)}
            className={`rounded-xl gap-2 ${hasActiveFilters ? 'border-[#91C4D9] text-[#5b9ebd]' : ''}`}
          >
            <Filter className="w-4 h-4" />
            Filters
            {activeFilterCount > 0 && (
              <span className="w-5 h-5 rounded-full bg-[#91C4D9] text-white text-xs flex items-center justify-center">
                {activeFilterCount}
              </span>
            )}
          </Button>
        </div>

        {/* Expanded Filters */}
        {showFilters && (
          <div className="p-4 bg-white rounded-xl border shadow-sm animate-in fade-in slide-in-from-top-2 duration-200">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Subject</label>
                <Select value={subject} onValueChange={setSubject}>
                  <SelectTrigger className="rounded-lg">
                    <GraduationCap className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {SUBJECTS.map((s) => (
                      <SelectItem key={s} value={s}>{s}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Province</label>
                <Select value={province} onValueChange={setProvince}>
                  <SelectTrigger className="rounded-lg">
                    <MapPin className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {PROVINCES.map((p) => (
                      <SelectItem key={p} value={p}>{p}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Service Type</label>
                <Select value={serviceType} onValueChange={setServiceType}>
                  <SelectTrigger className="rounded-lg">
                    <Clock className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {SERVICE_TYPES.map((t) => (
                      <SelectItem key={t} value={t}>{t}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Min Rating</label>
                <Select value={minRating} onValueChange={setMinRating}>
                  <SelectTrigger className="rounded-lg">
                    <Star className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="0">Any Rating</SelectItem>
                    <SelectItem value="3">3+ Stars</SelectItem>
                    <SelectItem value="3.5">3.5+ Stars</SelectItem>
                    <SelectItem value="4">4+ Stars</SelectItem>
                    <SelectItem value="4.5">4.5+ Stars</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">City</label>
                <Input
                  value={city}
                  onChange={(e) => setCity(e.target.value)}
                  placeholder="Enter city name..."
                  className="rounded-lg"
                />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Min Price (R/hr)</label>
                <Input
                  type="number"
                  value={priceMin}
                  onChange={(e) => setPriceMin(e.target.value)}
                  placeholder="Min"
                  className="rounded-lg"
                />
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1.5 block">Max Price (R/hr)</label>
                <Input
                  type="number"
                  value={priceMax}
                  onChange={(e) => setPriceMax(e.target.value)}
                  placeholder="Max"
                  className="rounded-lg"
                />
              </div>
              <div className="flex items-end">
                {hasActiveFilters && (
                  <Button variant="ghost" size="sm" onClick={clearFilters} className="rounded-lg text-gray-500 w-full">
                    <X className="w-3.5 h-3.5 mr-1" />
                    Clear all filters
                  </Button>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Results count */}
      {!loading && !error && (
        <p className="text-sm text-gray-500 mb-4">
          {filteredTutors.length} tutor{filteredTutors.length !== 1 ? 's' : ''} found
          {hasActiveFilters && ' (filtered)'}
        </p>
      )}

      {/* Map View Placeholder */}
      {!loading && !error && filteredTutors.length > 0 && (
        <Card className="mb-6 border-dashed">
          <CardContent className="p-6 flex items-center justify-center gap-3 text-gray-400">
            <Map className="w-5 h-5" />
            <span className="text-sm font-medium">Map view coming soon — Google Maps integration planned</span>
          </CardContent>
        </Card>
      )}

      {/* Loading */}
      {loading && (
        <div className="flex flex-col items-center justify-center py-16">
          <Loader2 className="w-8 h-8 text-[#5b9ebd] animate-spin mb-4" />
          <p className="text-gray-500">Finding the best tutors for you...</p>
        </div>
      )}

      {/* Error */}
      {error && !loading && (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
          <h3 className="text-lg font-semibold text-gray-900 mb-2">Could not load tutors</h3>
          <p className="text-gray-500 mb-4 max-w-md">{error}</p>
          <Button variant="outline" onClick={fetchTutors} className="rounded-xl">Try Again</Button>
        </div>
      )}

      {/* Empty state */}
      {!loading && !error && filteredTutors.length === 0 && (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="w-16 h-16 rounded-2xl bg-gray-100 flex items-center justify-center mb-4">
            <Users className="w-8 h-8 text-gray-400" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">No tutors found</h3>
          <p className="text-gray-500 max-w-md">
            {search || hasActiveFilters
              ? 'Try adjusting your search or filters to find more tutors.'
              : 'No tutors are available at the moment. Check back soon!'}
          </p>
          {hasActiveFilters && (
            <Button variant="outline" onClick={clearFilters} className="rounded-xl mt-4">Clear Filters</Button>
          )}
        </div>
      )}

      {/* Tutor Grid */}
      {!loading && !error && filteredTutors.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {filteredTutors.map((tutor) => (
            <Card
              key={tutor.id}
              className="group hover:shadow-md transition-all border-gray-200 hover:border-[#91C4D9]/40"
            >
              <CardHeader className="pb-3">
                <div className="flex items-start gap-3">
                  <div
                    className="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold text-sm shrink-0"
                    style={{ background: BRAND.colors.primaryGradient }}
                  >
                    {getInitials(tutor)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <CardTitle className="text-sm font-semibold truncate">
                      {tutor.user.firstName} {tutor.user.lastName}
                    </CardTitle>
                    <RatingStars rating={tutor.rating} />
                    <div className="flex items-center gap-2 mt-1 text-xs text-gray-500">
                      {tutor.totalSessions > 0 && (
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />{tutor.totalSessions} sessions
                        </span>
                      )}
                      {(tutor.province || tutor.city) && (
                        <span className="flex items-center gap-1">
                          <MapPin className="w-3 h-3" />
                          {[tutor.city, tutor.province].filter(Boolean).join(', ')}
                        </span>
                      )}
                    </div>
                  </div>
                  <Badge
                    variant="outline"
                    className={`text-[10px] shrink-0 ${
                      tutor.serviceType === 'online'
                        ? 'text-blue-600 border-blue-200 bg-blue-50'
                        : tutor.serviceType === 'in_person'
                          ? 'text-green-600 border-green-200 bg-green-50'
                          : 'text-purple-600 border-purple-200 bg-purple-50'
                    }`}
                  >
                    {tutor.serviceType === 'in_person' ? 'In-Person' : tutor.serviceType === 'both' ? 'Both' : 'Online'}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex flex-wrap gap-1">
                  {tutor.subjects.slice(0, 4).map((s) => (
                    <Badge key={s} variant="secondary" className="text-[10px] font-normal bg-[#f0f9ff] text-[#5b9ebd]">
                      {s}
                    </Badge>
                  ))}
                  {tutor.subjects.length > 4 && (
                    <Badge variant="secondary" className="text-[10px] font-normal text-gray-500">
                      +{tutor.subjects.length - 4}
                    </Badge>
                  )}
                </div>

                {tutor.bio && (
                  <p className="text-xs text-gray-600 line-clamp-2 leading-relaxed">{tutor.bio}</p>
                )}

                <div className="flex items-center justify-between pt-1">
                  <span className="text-lg font-bold" style={{ color: BRAND.colors.primaryDark }}>
                    R{tutor.hourlyRate || 0}<span className="text-xs font-normal text-gray-400">/hr</span>
                  </span>
                </div>

                <div className="flex gap-2">
                  <Button
                    size="sm"
                    onClick={() => setBookDialog(tutor)}
                    className="flex-1 rounded-lg text-xs h-8 text-white"
                    style={{ background: BRAND.colors.primaryGradient }}
                  >
                    <CalendarPlus className="w-3 h-3 mr-1" />
                    Book Now
                  </Button>
                  <Button size="sm" variant="outline" className="flex-1 rounded-lg text-xs h-8">
                    <Eye className="w-3 h-3 mr-1" />
                    View Profile
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Book Session Dialog */}
      <Dialog open={!!bookDialog} onOpenChange={(open) => !open && setBookDialog(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Book a Session</DialogTitle>
          </DialogHeader>
          {bookDialog && (
            <div className="space-y-4">
              <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                <div
                  className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm shrink-0"
                  style={{ background: BRAND.colors.primaryGradient }}
                >
                  {getInitials(bookDialog)}
                </div>
                <div>
                  <p className="text-sm font-semibold">
                    {bookDialog.user.firstName} {bookDialog.user.lastName}
                  </p>
                  <p className="text-xs text-gray-500">
                    R{bookDialog.hourlyRate || 0}/hr · {bookDialog.subjects.join(', ')}
                  </p>
                </div>
              </div>

              <div>
                <Label className="text-sm font-medium">Subject</Label>
                <Select value={bookSubject} onValueChange={setBookSubject}>
                  <SelectTrigger className="mt-1 rounded-lg">
                    <SelectValue placeholder="Select a subject" />
                  </SelectTrigger>
                  <SelectContent>
                    {bookDialog.subjects.map((s) => (
                      <SelectItem key={s} value={s}>{s}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label className="text-sm font-medium">Date & Time</Label>
                <Input
                  type="datetime-local"
                  value={bookDate}
                  onChange={(e) => setBookDate(e.target.value)}
                  className="mt-1 rounded-lg"
                />
              </div>

              <div>
                <Label className="text-sm font-medium">Notes (optional)</Label>
                <Textarea
                  value={bookNotes}
                  onChange={(e) => setBookNotes(e.target.value)}
                  placeholder="Any topics or areas you need help with..."
                  className="mt-1 rounded-lg"
                  rows={3}
                />
              </div>

              <DialogFooter className="gap-2">
                <Button variant="outline" onClick={() => setBookDialog(null)} className="rounded-lg">Cancel</Button>
                <Button
                  onClick={handleBook}
                  disabled={!bookSubject || !bookDate || bookingLoading}
                  className="rounded-lg text-white"
                  style={{ background: BRAND.colors.primaryGradient }}
                >
                  {bookingLoading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                  Confirm Booking
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
