'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 {
  Building2,
  Search,
  Sparkles,
  ExternalLink,
  MapPin,
  GraduationCap,
  Globe,
  Loader2,
  AlertCircle,
  Filter,
  X,
  MessageCircle,
  BookOpen,
  CreditCard,
  FileText,
} from 'lucide-react'

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

interface University {
  name: string
  description?: string
  sourceUrl?: string
  sourceName?: string
  province?: string
  type?: string
  courses?: string
  requirements?: string
  applicationFee?: string
  tuitionRange?: string
  website?: string
  lastVerified?: string
  aiGenerated?: boolean
  type2?: string
}

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

const PROVINCES = [
  'All Provinces',
  'Eastern Cape',
  'Free State',
  'Gauteng',
  'KwaZulu-Natal',
  'Limpopo',
  'Mpumalanga',
  'Northern Cape',
  'North West',
  'Western Cape',
]

const TYPES = ['All Types', 'university', 'tvet', 'technikons']

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

export default function UniversitiesPage() {
  const [universities, setUniversities] = useState<University[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [province, setProvince] = useState('All Provinces')
  const [uniType, setUniType] = useState('All Types')
  const [selectedUni, setSelectedUni] = useState<University | null>(null)
  const [showFilters, setShowFilters] = useState(false)

  const fetchUniversities = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams()
      if (province !== 'All Provinces') params.set('province', province)
      if (uniType !== 'All Types') params.set('type', uniType)
      if (search) params.set('search', search)

      const res = await fetch(`/api/ai/browse-universities?${params.toString()}`)
      if (!res.ok) throw new Error('Failed to fetch universities')
      const data = await res.json()
      setUniversities(data.universities || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred')
    } finally {
      setLoading(false)
    }
  }, [province, uniType, search])

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

  const handleAskAI = (uni: University) => {
    const query = encodeURIComponent(
      `Tell me about ${uni.name}${uni.province ? ` in ${uni.province}` : ''}. What are the admission requirements, top courses, and how do I apply?`
    )
    window.location.href = `/ai-coach?msg=${query}`
  }

  const hasActiveFilters = province !== 'All Provinces' || uniType !== 'All Types'

  const formatType = (type?: string) => {
    if (!type) return 'General'
    return type.charAt(0).toUpperCase() + type.slice(1)
  }

  return (
    <div className="max-w-6xl 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: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}>
              <Building2 className="w-4 h-4 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900">University Explorer</h1>
          </div>
          <p className="text-sm text-gray-500">
            Explore South African universities, courses, and admission requirements
          </p>
        </div>
        <Button
          onClick={() => {
            const query = encodeURIComponent('I want to explore South African universities. What are the top universities, their courses, and admission requirements? Help me choose based on my interests.')
            window.location.href = `/ai-coach?msg=${query}`
          }}
          className="rounded-xl"
          style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}
        >
          <Sparkles className="w-4 h-4 mr-2" />
          AI Application Assistant
        </Button>
      </div>

      {/* Search and Filters */}
      <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 universities by name..."
              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
            {hasActiveFilters && (
              <span className="w-5 h-5 rounded-full bg-[#91C4D9] text-white text-xs flex items-center justify-center">
                {[province !== 'All Provinces', uniType !== 'All Types'].filter(Boolean).length}
              </span>
            )}
          </Button>
        </div>

        {showFilters && (
          <div className="flex flex-wrap gap-3 p-4 bg-white rounded-xl border animate-in fade-in slide-in-from-top-2 duration-200">
            <div className="min-w-[180px]">
              <label className="text-xs font-medium text-gray-500 mb-1 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 className="min-w-[180px]">
              <label className="text-xs font-medium text-gray-500 mb-1 block">Institution Type</label>
              <Select value={uniType} onValueChange={setUniType}>
                <SelectTrigger className="rounded-lg">
                  <GraduationCap className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {TYPES.map((t) => (
                    <SelectItem key={t} value={t}>
                      {t === 'All Types' ? 'All Types' : t.toUpperCase()}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {hasActiveFilters && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setProvince('All Provinces')
                  setUniType('All Types')
                }}
                className="self-end text-gray-500"
              >
                Clear all
              </Button>
            )}
          </div>
        )}
      </div>

      {/* Loading state */}
      {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">Loading university information...</p>
        </div>
      )}

      {/* Error state */}
      {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 universities</h3>
          <p className="text-gray-500 mb-4 max-w-md">{error}</p>
          <Button variant="outline" onClick={fetchUniversities} className="rounded-xl">
            Try Again
          </Button>
        </div>
      )}

      {/* Empty state */}
      {!loading && !error && universities.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">
            <Building2 className="w-8 h-8 text-gray-400" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">No universities found</h3>
          <p className="text-gray-500 max-w-md">
            {search || hasActiveFilters
              ? 'Try adjusting your search or filters to find more institutions.'
              : 'No university data is available at the moment. Use the AI Coach to ask about specific universities!'}
          </p>
        </div>
      )}

      {/* University cards */}
      {!loading && !error && universities.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {universities.map((uni, index) => (
            <Card
              key={`${uni.name}-${index}`}
              className={`group hover:shadow-md transition-all border-gray-200 hover:border-[#91C4D9]/40 cursor-pointer ${
                selectedUni?.name === uni.name && selectedUni?.sourceUrl === uni.sourceUrl
                  ? 'ring-2 ring-[#91C4D9] border-[#91C4D9]'
                  : ''
              }`}
              onClick={() =>
                setSelectedUni(
                  selectedUni?.name === uni.name ? null : uni
                )
              }
            >
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between gap-2">
                  <CardTitle className="text-sm font-semibold leading-snug line-clamp-2">
                    {uni.name}
                  </CardTitle>
                  <Badge variant="secondary" className="shrink-0 text-[10px]">
                    {formatType(uni.type || uni.type2)}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                {uni.description && (
                  <p className="text-xs text-gray-600 line-clamp-3 leading-relaxed">
                    {uni.description}
                  </p>
                )}

                <div className="flex flex-wrap gap-1.5">
                  {uni.province && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <MapPin className="w-3 h-3 mr-1" />
                      {uni.province}
                    </Badge>
                  )}
                  {uni.tuitionRange && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <CreditCard className="w-3 h-3 mr-1" />
                      {uni.tuitionRange}
                    </Badge>
                  )}
                  {uni.applicationFee && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <FileText className="w-3 h-3 mr-1" />
                      App fee: {uni.applicationFee}
                    </Badge>
                  )}
                </div>

                {/* Expanded details */}
                {selectedUni?.name === uni.name && (
                  <div className="pt-2 border-t space-y-2 animate-in fade-in slide-in-from-top-2 duration-200">
                    {uni.courses && (
                      <div>
                        <p className="text-[10px] font-semibold text-gray-500 uppercase mb-1">Courses</p>
                        <p className="text-xs text-gray-600">
                          {typeof uni.courses === 'string'
                            ? uni.courses.slice(0, 200)
                            : Array.isArray(uni.courses)
                              ? (uni.courses as string[]).slice(0, 5).join(', ')
                              : ''}
                        </p>
                      </div>
                    )}
                    {uni.requirements && (
                      <div>
                        <p className="text-[10px] font-semibold text-gray-500 uppercase mb-1">Requirements</p>
                        <p className="text-xs text-gray-600">
                          {typeof uni.requirements === 'string'
                            ? uni.requirements.slice(0, 200)
                            : Array.isArray(uni.requirements)
                              ? (uni.requirements as string[]).slice(0, 5).join(', ')
                              : ''}
                        </p>
                      </div>
                    )}
                  </div>
                )}

                <div className="flex gap-2 pt-1">
                  {(uni.sourceUrl || uni.website) && (
                    <a
                      href={uni.website || uni.sourceUrl || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex-1"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Button
                        size="sm"
                        variant="outline"
                        className="w-full rounded-lg text-xs h-8"
                      >
                        <Globe className="w-3 h-3 mr-1" />
                        Visit
                      </Button>
                    </a>
                  )}
                  <Button
                    size="sm"
                    variant="ghost"
                    className="rounded-lg text-xs h-8 text-[#5b9ebd] hover:text-[#5b9ebd] hover:bg-[#f0f9ff]"
                    onClick={(e) => {
                      e.stopPropagation()
                      handleAskAI(uni)
                    }}
                  >
                    <MessageCircle className="w-3 h-3 mr-1" />
                    Ask AI
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}
