'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Calendar, FileText, Filter, Search, Clock, Tag, ExternalLink, Download } from 'lucide-react'
import Link from 'next/link'
import { tendersApi, Tender } from '@/lib/api'

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return 'Date TBA'
  const date = new Date(dateString)
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
}

const getDaysUntil = (dateString: string) => {
  const closingDate = new Date(dateString)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  closingDate.setHours(0, 0, 0, 0)
  
  const diffTime = closingDate.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays
}

const getStatusColor = (status: string, closingDate: string) => {
  const daysUntil = getDaysUntil(closingDate)
  
  if (status === 'awarded') return 'bg-green-500/20 text-green-300 border-green-500/30'
  if (status === 'closed') return 'bg-gray-500/20 text-gray-300 border-gray-500/30'
  if (daysUntil <= 7) return 'bg-red-500/20 text-red-300 border-red-500/30'
  if (daysUntil <= 30) return 'bg-orange-500/20 text-orange-300 border-orange-500/30'
  return 'bg-blue-500/20 text-blue-300 border-blue-500/30'
}

export default function TendersPage() {
  const [tenders, setTenders] = useState<Tender[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [selectedStatus, setSelectedStatus] = useState<'all' | 'open' | 'closed'>('all')

  useEffect(() => {
    const fetchTenders = async () => {
      try {
        const params: any = { limit: 50 }
        if (selectedStatus === 'open') params.open = 'true'
        if (selectedStatus === 'closed') params.closed = 'true'
        if (selectedCategory) params.category = selectedCategory
        
        const result = await tendersApi.getAll(params)
        setTenders(result.data)
      } catch (error) {
        console.error('Error fetching tenders:', error)
        setTenders([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchTenders()
  }, [selectedCategory, selectedStatus])

  const filteredTenders = tenders.filter(tender => {
    const matchesSearch = 
      tender.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      tender.tenderNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      tender.description.toLowerCase().includes(searchTerm.toLowerCase())
    return matchesSearch
  })

  const categories = Array.from(new Set(tenders.map(t => t.category).filter(Boolean)))

  return (
    <div className="min-h-screen py-12 px-4">
      <div className="max-w-[1200px] mx-auto">
        <div className="glass-page rounded-2xl p-8 md:p-12 shadow-2xl">
          {/* Header Section */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="text-center mb-12"
          >
            <div className="flex items-center justify-center gap-3 mb-4">
              <FileText className="w-8 h-8 text-primary-light" />
              <h1 className="text-4xl md:text-5xl font-bold text-white">Tenders</h1>
            </div>
            <p className="text-white/70 text-lg mb-6">
              View current tenders, submit proposals, and access tender documents
            </p>
            <div className="w-24 h-1 bg-primary mx-auto"></div>
          </motion.div>

          {/* Filters and Search */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="mb-8 space-y-4"
          >
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/50" />
              <input
                type="text"
                placeholder="Search tenders by title, number, or description..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-12 pr-4 py-3 glass rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>

            {/* Filters */}
            <div className="flex flex-wrap gap-4">
              <div className="flex items-center gap-2">
                <Filter className="w-5 h-5 text-white/70" />
                <span className="text-white/90 font-semibold">Status:</span>
              </div>
              <div className="flex flex-wrap gap-3">
                <button
                  onClick={() => setSelectedStatus('all')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'all'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  All
                </button>
                <button
                  onClick={() => setSelectedStatus('open')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'open'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  Open
                </button>
                <button
                  onClick={() => setSelectedStatus('closed')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'closed'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  Closed
                </button>
              </div>
            </div>

            {/* Category Filter */}
            {categories.length > 0 && (
              <div className="flex flex-wrap gap-3">
                <button
                  onClick={() => setSelectedCategory(null)}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedCategory === null
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  All Categories
                </button>
                {categories.map((category) => (
                  <button
                    key={category}
                    onClick={() => setSelectedCategory(category)}
                    className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                      selectedCategory === category
                        ? 'bg-primary text-white'
                        : 'glass text-white/80 hover:bg-white/10'
                    }`}
                  >
                    {category}
                  </button>
                ))}
              </div>
            )}
          </motion.div>

          {/* Tenders List */}
          {isLoading ? (
            <div className="text-center py-12">
              <div className="text-white/70">Loading tenders...</div>
            </div>
          ) : filteredTenders.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="text-center py-12"
            >
              <FileText className="w-16 h-16 text-white/30 mx-auto mb-4" />
              <p className="text-white/60 text-lg">No tenders found</p>
              <p className="text-white/40 text-sm mt-2">
                {searchTerm || selectedCategory || selectedStatus !== 'all'
                  ? 'Try adjusting your filters or search terms.'
                  : 'Check back soon for new tenders.'}
              </p>
            </motion.div>
          ) : (
            <div className="grid grid-cols-1 gap-6">
              {filteredTenders.map((tender, index) => {
                const daysUntil = getDaysUntil(tender.closingDate)
                const isUrgent = daysUntil >= 0 && daysUntil <= 7 && tender.status === 'open'
                
                return (
                  <motion.div
                    key={tender._id}
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: index * 0.1 }}
                    whileHover={{ y: -8, scale: 1.02 }}
                    className="glass rounded-xl p-6 shadow-xl glass-hover border-2 border-white/10 hover:border-primary/30 transition-all duration-300"
                  >
                    <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                      <div className="flex-1">
                        {/* Urgent Badge */}
                        {isUrgent && (
                          <motion.div
                            animate={{ scale: [1, 1.05, 1] }}
                            transition={{ duration: 2, repeat: Infinity }}
                            className="inline-block bg-red-500 text-white px-3 py-1 rounded-full text-xs font-bold mb-3"
                          >
                            URGENT - {daysUntil === 0 ? 'CLOSES TODAY' : `${daysUntil} DAYS LEFT`}
                          </motion.div>
                        )}

                        {/* Tender Number */}
                        <div className="flex items-center gap-2 mb-2">
                          <Tag className="w-4 h-4 text-primary-light" />
                          <span className="text-primary-light font-semibold text-sm">
                            {tender.tenderNumber}
                          </span>
                          <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(tender.status, tender.closingDate)}`}>
                            {tender.status.toUpperCase()}
                          </span>
                        </div>

                        {/* Title */}
                        <h3 className="text-2xl font-bold text-white mb-3 hover:text-primary-light transition-colors">
                          {tender.title}
                        </h3>

                        {/* Description */}
                        <p className="text-white/70 text-sm mb-4 line-clamp-2">
                          {tender.description}
                        </p>

                        {/* Details */}
                        <div className="flex flex-wrap gap-4 text-sm text-white/70">
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-primary-light" />
                            <span>Closes: {formatDate(tender.closingDate)}</span>
                            {tender.status === 'open' && daysUntil >= 0 && (
                              <span className="text-primary-light font-semibold">
                                ({daysUntil} {daysUntil === 1 ? 'day' : 'days'} left)
                              </span>
                            )}
                          </div>
                          {tender.category && (
                            <div className="flex items-center gap-2">
                              <Tag className="w-4 h-4 text-primary-light" />
                              <span>{tender.category}</span>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="flex flex-col gap-2 md:min-w-[200px]">
                        {tender.documentUrl && (
                          <a
                            href={tender.documentUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center justify-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg font-semibold transition-all hover:scale-105"
                          >
                            <Download className="w-4 h-4" />
                            Download Documents
                          </a>
                        )}
                        {tender.link && (
                          <a
                            href={tender.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center justify-center gap-2 glass text-white px-4 py-2 rounded-lg font-semibold transition-all hover:bg-white/10"
                          >
                            <ExternalLink className="w-4 h-4" />
                            View Details
                          </a>
                        )}
                      </div>
                    </div>
                  </motion.div>
                )
              })}
            </div>
          )}

          {/* Quick Links */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.4 }}
            className="mt-12 pt-8 border-t border-white/10"
          >
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Link
                href="/tenders/tenders-awarded"
                className="glass rounded-lg p-4 hover:bg-white/10 transition-all text-center"
              >
                <h3 className="text-white font-semibold mb-2">Tenders Awarded</h3>
                <p className="text-white/70 text-sm">View awarded tenders</p>
              </Link>
              <Link
                href="/tenders/vendor-registration"
                className="glass rounded-lg p-4 hover:bg-white/10 transition-all text-center"
              >
                <h3 className="text-white font-semibold mb-2">Vendor Registration</h3>
                <p className="text-white/70 text-sm">Register as a vendor</p>
              </Link>
              <Link
                href="/tenders/request-quotations"
                className="glass rounded-lg p-4 hover:bg-white/10 transition-all text-center"
              >
                <h3 className="text-white font-semibold mb-2">Request for Quotations</h3>
                <p className="text-white/70 text-sm">Submit RFQ</p>
              </Link>
            </div>
          </motion.div>
        </div>
      </div>
    </div>
  )
}
