import { useState, useEffect } from 'react'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Clock, Package, AlertCircle, CheckCircle, Loader, Filter, FileText } from 'lucide-react'
import { api } from '../lib/api'

interface ChangelogEntry {
  version: string
  date: string
  title: string
  type: 'major' | 'minor' | 'patch'
  changes: string[]
  breaking_changes: string[]
  notes: string
}

type VersionType = 'major' | 'minor' | 'patch'

export default function Changelog() {
  useBreadcrumb(breadcrumbConfig['/changelog'])
  const [versions, setVersions] = useState<ChangelogEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [typeFilter, setTypeFilter] = useState<VersionType[]>(['major', 'minor', 'patch'])

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

  const loadChangelog = async () => {
    try {
      setLoading(true)
      const response = await api.get<{ versions: ChangelogEntry[] }>('/changelog')
      setVersions(response.versions || [])
    } catch (error) {
      console.error('Failed to load changelog:', error)
      setError('Failed to load changelog')
    } finally {
      setLoading(false)
    }
  }

  const toggleTypeFilter = (type: VersionType) => {
    setTypeFilter(prev =>
      prev.includes(type)
        ? prev.filter(t => t !== type)
        : [...prev, type]
    )
  }

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'major':
        return 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800'
      case 'minor':
        return 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800'
      case 'patch':
        return 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800'
      default:
        return 'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 border-slate-200 dark:border-slate-700'
    }
  }

  const getTypeButtonColor = (type: VersionType, active: boolean) => {
    if (!active) {
      return 'bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500 border-slate-200 dark:border-slate-600'
    }
    switch (type) {
      case 'major':
        return 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 border-red-300 dark:border-red-700'
      case 'minor':
        return 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-blue-300 dark:border-blue-700'
      case 'patch':
        return 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 border-green-300 dark:border-green-700'
      default:
        return 'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 border-slate-200 dark:border-slate-700'
    }
  }

  const filteredVersions = versions.filter(v => typeFilter.includes(v.type as VersionType))

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader className="w-8 h-8 animate-spin text-blue-600 dark:text-blue-400" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div className="flex items-center space-x-2">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
          <p className="text-red-700 dark:text-red-400">{error}</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <FileText className="w-8 h-8 text-blue-500" />
            Change Log
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Showing {filteredVersions.length} of {versions.length} version{versions.length !== 1 ? 's' : ''}
          </p>
        </div>

        {/* Filter Buttons */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
          <div className="flex items-center space-x-2">
            <Filter className="w-4 h-4 text-slate-500 dark:text-slate-400" />
            <span className="text-sm font-medium text-slate-600 dark:text-slate-400">Filter:</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {(['major', 'minor', 'patch'] as VersionType[]).map(type => (
              <button
                key={type}
                onClick={() => toggleTypeFilter(type)}
                className={`px-3 py-1.5 text-xs font-medium rounded-lg border transition-all touch-manipulation ${getTypeButtonColor(
                  type,
                  typeFilter.includes(type)
                )}`}
              >
                {type.charAt(0).toUpperCase() + type.slice(1)}
              </button>
            ))}
            {typeFilter.length < 3 && (
              <button
                onClick={() => setTypeFilter(['major', 'minor', 'patch'])}
                className="px-3 py-1.5 text-xs font-medium text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300 transition-colors"
              >
                Reset
              </button>
            )}
          </div>
        </div>
      </div>

      {filteredVersions.length === 0 ? (
        <div className="bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 rounded-lg p-8 text-center">
          <Package className="w-12 h-12 text-slate-400 dark:text-slate-500 mx-auto mb-3" />
          <p className="text-slate-600 dark:text-slate-400">No versions match the selected filters</p>
          <button
            onClick={() => setTypeFilter(['major', 'minor', 'patch'])}
            className="mt-3 px-4 py-2 text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
          >
            Reset filters
          </button>
        </div>
      ) : (
        <div className="space-y-6">
          {filteredVersions.map((entry) => (
            <div
              key={entry.version}
              className="card-glass-hover rounded-xl overflow-hidden"
            >
            {/* Header */}
            <div className="bg-slate-50 dark:bg-slate-800/50 border-b border-slate-200 dark:border-slate-800 p-4">
              <div className="flex items-center justify-between flex-wrap gap-2">
                <div className="flex items-center space-x-3">
                  <Package className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                  <h2 className="text-xl font-semibold text-slate-900 dark:text-slate-100">
                    v{entry.version}
                  </h2>
                  <span
                    className={`px-2 py-0.5 text-xs font-medium rounded-full border ${getTypeColor(
                      entry.type
                    )}`}
                  >
                    {entry.type}
                  </span>
                </div>
                <div className="flex items-center space-x-2 text-sm text-slate-500 dark:text-slate-400">
                  <Clock className="w-4 h-4" />
                  <span>{entry.date}</span>
                </div>
              </div>
              <p className="mt-2 text-slate-700 dark:text-slate-300 font-medium">{entry.title}</p>
            </div>

            {/* Content */}
            <div className="p-6 space-y-6">
              {/* Breaking Changes */}
              {entry.breaking_changes && entry.breaking_changes.length > 0 && (
                <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                  <div className="flex items-center space-x-2 mb-2">
                    <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
                    <h3 className="font-semibold text-red-900 dark:text-red-100">Breaking Changes</h3>
                  </div>
                  <ul className="space-y-1">
                    {entry.breaking_changes.map((change, idx) => (
                      <li
                        key={idx}
                        className="text-sm text-red-700 dark:text-red-300 ml-4 list-disc"
                      >
                        {change}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Changes */}
              {entry.changes && entry.changes.length > 0 && (
                <div>
                  <h3 className="font-semibold text-slate-900 dark:text-slate-100 mb-3 flex items-center space-x-2">
                    <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400" />
                    <span>Changes</span>
                  </h3>
                  <ul className="space-y-2">
                    {entry.changes.map((change, idx) => (
                      <li
                        key={idx}
                        className="text-sm text-slate-700 dark:text-slate-300 ml-4 list-none"
                      >
                        {change}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Notes */}
              {entry.notes && (
                <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                  <p className="text-sm text-blue-900 dark:text-blue-100">{entry.notes}</p>
                </div>
              )}
            </div>
          </div>
        ))}
        </div>
      )}
    </div>
  )
}
