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

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

interface Bursary {
  title: string
  description?: string
  sourceUrl?: string
  sourceName?: string
  provider?: string
  closingDate?: string
  value?: string
  province?: string
  fieldOfStudy?: string
  level?: string
  isVerified?: boolean
  type?: string
}

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

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

const FIELDS = [
  'All Fields',
  'Engineering',
  'Medicine',
  'Law',
  'Business',
  'IT',
  'Science',
  'Arts',
  'Teaching',
  'Accounting',
]

const LEVELS = ['All Levels', 'Undergraduate', 'Postgraduate', 'Any']

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

export default function BursaryPage() {
  const [bursaries, setBursaries] = useState<Bursary[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')
  const [province, setProvince] = useState('All Provinces')
  const [field, setField] = useState('All Fields')
  const [level, setLevel] = useState('All Levels')
  const [smartMatchLoading, setSmartMatchLoading] = useState(false)
  const [aiRecommendations, setAiRecommendations] = useState<string | null>(null)
  const [showFilters, setShowFilters] = useState(false)

  const fetchBursaries = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams()
      if (province !== 'All Provinces') params.set('province', province)
      if (field !== 'All Fields') params.set('field', field)
      if (level !== 'All Levels') params.set('level', level.toLowerCase())

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

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

  // Filter by search
  const filteredBursaries = bursaries.filter((b) => {
    if (!search) return true
    const q = search.toLowerCase()
    return (
      b.title.toLowerCase().includes(q) ||
      b.description?.toLowerCase().includes(q) ||
      b.provider?.toLowerCase().includes(q) ||
      b.fieldOfStudy?.toLowerCase().includes(q)
    )
  })

  const handleSmartMatch = async () => {
    setSmartMatchLoading(true)
    setAiRecommendations(null)
    try {
      const res = await fetch('/api/ai/smart-match', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      })
      if (!res.ok) throw new Error('Failed to get AI recommendations')
      const data = await res.json()
      const recs = data.recommendations
      if (recs?.bursaries?.length > 0) {
        setAiRecommendations(
          recs.bursaries
            .map((b: { title?: string; reason?: string; priority?: string }) =>
              `${b.title || 'Bursary'}${b.reason ? ` — ${b.reason}` : ''}${b.priority ? ` [${b.priority}]` : ''}`
            )
            .join('\n')
        )
      } else {
        setAiRecommendations(recs?.summary || 'No specific bursary matches found. Try chatting with the AI Coach for personalised advice!')
      }
    } catch (err) {
      setAiRecommendations(
        'Could not generate AI recommendations right now. The AI model may be starting up.'
      )
    } finally {
      setSmartMatchLoading(false)
    }
  }

  const handleAskAI = (bursary: Bursary) => {
    const query = encodeURIComponent(
      `Tell me more about this bursary: "${bursary.title}". ${bursary.description ? `Description: ${bursary.description}` : ''} How can I apply and what are the requirements?`
    )
    window.location.href = `/ai-coach?msg=${query}`
  }

  const hasActiveFilters = province !== 'All Provinces' || field !== 'All Fields' || level !== 'All Levels'

  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%)' }}>
              <Award className="w-4 h-4 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900">Bursary Explorer</h1>
          </div>
          <p className="text-sm text-gray-500">
            Find bursaries and scholarships for South African students
          </p>
        </div>
        <Button
          onClick={handleSmartMatch}
          disabled={smartMatchLoading}
          className="rounded-xl"
          style={{ background: 'linear-gradient(135deg, #91C4D9 0%, #5b9ebd 100%)' }}
        >
          {smartMatchLoading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Finding Matches...
            </>
          ) : (
            <>
              <Sparkles className="w-4 h-4 mr-2" />
              Find My Bursaries
            </>
          )}
        </Button>
      </div>

      {/* AI Recommendations */}
      {aiRecommendations && (
        <Card className="mb-6 border-[#91C4D9]/30 bg-[#f0f9ff]">
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Sparkles className="w-4 h-4 text-[#5b9ebd]" />
              AI Smart Match Results
            </CardTitle>
          </CardHeader>
          <CardContent>
            <pre className="whitespace-pre-wrap text-sm text-gray-700 font-sans leading-relaxed">
              {aiRecommendations}
            </pre>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setAiRecommendations(null)}
              className="mt-2 text-gray-500"
            >
              <X className="w-3 h-3 mr-1" />
              Dismiss
            </Button>
          </CardContent>
        </Card>
      )}

      {/* 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 bursaries by name, field, or provider..."
              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', field !== 'All Fields', level !== 'All Levels'].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">Field of Study</label>
              <Select value={field} onValueChange={setField}>
                <SelectTrigger className="rounded-lg">
                  <BookOpen className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {FIELDS.map((f) => (
                    <SelectItem key={f} value={f}>{f}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="min-w-[180px]">
              <label className="text-xs font-medium text-gray-500 mb-1 block">Level</label>
              <Select value={level} onValueChange={setLevel}>
                <SelectTrigger className="rounded-lg">
                  <GraduationCap className="w-3.5 h-3.5 mr-1.5 text-gray-400" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {LEVELS.map((l) => (
                    <SelectItem key={l} value={l}>{l}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {hasActiveFilters && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  setProvince('All Provinces')
                  setField('All Fields')
                  setLevel('All Levels')
                }}
                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">Searching for bursaries...</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 bursaries</h3>
          <p className="text-gray-500 mb-4 max-w-md">{error}</p>
          <Button variant="outline" onClick={fetchBursaries} className="rounded-xl">
            Try Again
          </Button>
        </div>
      )}

      {/* Empty state */}
      {!loading && !error && filteredBursaries.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">
            <Award className="w-8 h-8 text-gray-400" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">No bursaries found</h3>
          <p className="text-gray-500 max-w-md">
            {search || hasActiveFilters
              ? 'Try adjusting your search or filters to find more bursaries.'
              : 'No bursaries are available at the moment. Check back soon or use the AI Coach to ask about funding options!'}
          </p>
        </div>
      )}

      {/* Bursary cards */}
      {!loading && !error && filteredBursaries.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredBursaries.map((bursary, index) => (
            <Card
              key={`${bursary.title}-${index}`}
              className="group hover:shadow-md transition-all border-gray-200 hover:border-[#91C4D9]/40"
            >
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between gap-2">
                  <CardTitle className="text-sm font-semibold leading-snug line-clamp-2">
                    {bursary.title}
                  </CardTitle>
                  {bursary.isVerified && (
                    <Badge variant="secondary" className="shrink-0 text-[10px] bg-green-50 text-green-700">
                      Verified
                    </Badge>
                  )}
                </div>
                {bursary.provider && (
                  <p className="text-xs text-gray-500">{bursary.provider}</p>
                )}
              </CardHeader>
              <CardContent className="space-y-3">
                {bursary.description && (
                  <p className="text-xs text-gray-600 line-clamp-3 leading-relaxed">
                    {bursary.description}
                  </p>
                )}

                <div className="flex flex-wrap gap-1.5">
                  {bursary.value && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      {bursary.value}
                    </Badge>
                  )}
                  {bursary.closingDate && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <Calendar className="w-3 h-3 mr-1" />
                      {new Date(bursary.closingDate).toLocaleDateString('en-ZA', {
                        month: 'short',
                        day: 'numeric',
                        year: 'numeric',
                      })}
                    </Badge>
                  )}
                  {bursary.province && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <MapPin className="w-3 h-3 mr-1" />
                      {bursary.province}
                    </Badge>
                  )}
                  {bursary.fieldOfStudy && (
                    <Badge variant="outline" className="text-[10px] font-normal">
                      <BookOpen className="w-3 h-3 mr-1" />
                      {bursary.fieldOfStudy}
                    </Badge>
                  )}
                </div>

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