import { useState, useEffect } from 'react'
import { useAuth } from '@/hooks'
import { useNavigate } from 'react-router-dom'
import { groupService, Group } from '@/services'

/**
 * Helper function to convert hex color to RGB values
 */
function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null
}

/**
 * Helper function to determine if text should be light or dark based on background color
 */
function getContrastTextColor(hexColor: string): string {
  const rgb = hexToRgb(hexColor)
  if (!rgb) return '#000000'
  
  // Calculate luminance
  const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255
  return luminance > 0.5 ? '#000000' : '#ffffff'
}

/**
 * Helper function to lighten a hex color for hover state
 */
function lightenColor(hex: string, percent: number): string {
  const rgb = hexToRgb(hex)
  if (!rgb) return hex
  
  const lighten = (value: number) => Math.min(255, Math.floor(value + (255 - value) * percent))
  
  const r = lighten(rgb.r).toString(16).padStart(2, '0')
  const g = lighten(rgb.g).toString(16).padStart(2, '0')
  const b = lighten(rgb.b).toString(16).padStart(2, '0')
  
  return `#${r}${g}${b}`
}

/**
 * Helper function to darken a hex color for border
 */
function darkenColor(hex: string, percent: number): string {
  const rgb = hexToRgb(hex)
  if (!rgb) return hex
  
  const darken = (value: number) => Math.max(0, Math.floor(value * (1 - percent)))
  
  const r = darken(rgb.r).toString(16).padStart(2, '0')
  const g = darken(rgb.g).toString(16).padStart(2, '0')
  const b = darken(rgb.b).toString(16).padStart(2, '0')
  
  return `#${r}${g}${b}`
}

export default function DashboardPage() {
  const { user, logout } = useAuth()
  const navigate = useNavigate()
  const [groups, setGroups] = useState<Group[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [hoveredGroup, setHoveredGroup] = useState<number | null>(null)

  useEffect(() => {
    const fetchGroups = async () => {
      try {
        setLoading(true)
        const fetchedGroups = await groupService.getGroups()
        setGroups(fetchedGroups)
        setError(null)
      } catch (err) {
        console.error('Failed to fetch groups:', err)
        setError('Failed to load groups')
      } finally {
        setLoading(false)
      }
    }

    fetchGroups()
  }, [])

  const handleCategoryClick = (groupName: string) => {
    navigate(`/requirements?group=${encodeURIComponent(groupName)}`)
  }

  const handleMyRequirementsClick = () => {
    navigate('/requirements')
  }

  return (
    <div className="min-h-screen bg-white">
      {/* Header */}
      <header className="py-6 text-center">
        <h1 className="text-3xl font-semibold text-teal-700">
          Digital Twin Requirements Tool
        </h1>
      </header>

      {/* Top Bar */}
      <div className="border-y border-gray-200 py-3 px-8">
        <div className="flex items-center justify-between max-w-7xl mx-auto">
          {/* Breadcrumb */}
          <div className="text-sm">
            <span className="text-gray-600">Projects</span>
            <span className="mx-2 text-gray-400">»</span>
            <span className="font-semibold text-gray-900">PeTWIN</span>
          </div>

          {/* Language Toggle */}
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <span>English</span>
            <div className="relative inline-flex h-5 w-10 items-center rounded-full bg-gray-300">
              <span className="inline-block h-4 w-4 transform rounded-full bg-white shadow-sm translate-x-0.5" />
            </div>
            <span>Portuguese</span>
          </div>

          {/* Admin Panel Button */}
          <button className="px-4 py-1.5 border border-gray-400 rounded text-sm font-medium text-gray-700 hover:bg-gray-50">
            Admin Panel
          </button>

          {/* User Info */}
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2">
              <svg className="w-5 h-5 text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
              </svg>
              <span className="text-sm text-gray-700">
                {user?.full_name || user?.preferred_username || 'User'}{' '}
                <span className="text-gray-500">(admin)</span>
              </span>
            </div>
            <button
              onClick={logout}
              className="px-3 py-1 border border-gray-400 rounded text-sm text-gray-700 hover:bg-gray-50"
            >
              Logout
            </button>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-8 py-8">
        <div className="flex gap-12">
          {/* Left Sidebar */}
          <div className="w-64 flex-shrink-0">
            {/* Requirements Search */}
            <div className="mb-8">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Requirements Search</h2>
              <p className="text-sm text-teal-600">
                Search for specific elements by name or symbol.
              </p>
            </div>

            {/* Create a Requirement */}
            <div className="mb-8">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Create a Requirement</h2>
              <p className="text-sm text-teal-600">
                Register a new Requirement.
              </p>
            </div>

            {/* Last Viewed Requirement */}
            <div className="mb-8">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Last Viewed Requirement:</h2>
              <p className="text-sm text-gray-600 mb-1">No requirement accessed yet</p>
              <a href="#" className="text-sm text-teal-600 hover:underline">
                View More
              </a>
            </div>

            {/* My Requirements */}
            <div className="mb-8 cursor-pointer" onClick={handleMyRequirementsClick}>
              <h2 className="text-lg font-bold text-gray-800 mb-1 hover:text-teal-700">My Requirements</h2>
              <p className="text-sm text-teal-600">
                View your requirements and their properties.
              </p>
            </div>

            {/* Requirement Report */}
            <div className="mb-8">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Requirement Report</h2>
              <p className="text-sm text-teal-600">
                Generate the current status of this projects requirements in PDF format
              </p>
            </div>
          </div>

          {/* Right Content - Quick Search Filters */}
          <div className="flex-1">
            <h2 className="text-xl font-semibold text-gray-700 mb-6 text-center">
              Quick Search Filters
            </h2>

            {/* Loading State */}
            {loading && (
              <div className="flex justify-center items-center min-h-[200px]">
                <div className="text-gray-500">Loading groups...</div>
              </div>
            )}

            {/* Error State */}
            {error && (
              <div className="flex justify-center items-center min-h-[200px]">
                <div className="text-red-500">{error}</div>
              </div>
            )}

            {/* Groups Grid */}
            {!loading && !error && groups.length > 0 && (
              <div className="grid grid-cols-3 gap-4 max-w-2xl mx-auto">
                {groups.map((group) => {
                  const isHovered = hoveredGroup === group.id
                  const bgColor = isHovered 
                    ? lightenColor(group.hex_color, 0.2) 
                    : group.hex_color
                  const borderColor = darkenColor(group.hex_color, 0.2)
                  const textColor = getContrastTextColor(group.hex_color)

                  return (
                    <div
                      key={group.id}
                      onClick={() => handleCategoryClick(group.group_name)}
                      onMouseEnter={() => setHoveredGroup(group.id)}
                      onMouseLeave={() => setHoveredGroup(null)}
                      className="flex flex-col items-center justify-center p-6 cursor-pointer transition-colors min-h-[120px] rounded-lg"
                      style={{
                        backgroundColor: bgColor,
                        borderWidth: '2px',
                        borderStyle: 'solid',
                        borderColor: borderColor,
                      }}
                    >
                      <span 
                        className="text-sm font-semibold text-center"
                        style={{ color: textColor }}
                      >
                        {group.group_name}
                      </span>
                    </div>
                  )
                })}
              </div>
            )}

            {/* Empty State */}
            {!loading && !error && groups.length === 0 && (
              <div className="flex justify-center items-center min-h-[200px]">
                <div className="text-gray-500">No groups found</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

