import { useEffect, useState } from 'react'
import { useAuth } from '../context/AuthContext'
import { photosApi, PhotoSearchResult } from '../api/photos'
import apiClient from '../api/client'

export default function Dashboard() {
  const { username: _username } = useAuth()
  const [samplePhotos, setSamplePhotos] = useState<PhotoSearchResult[]>([])
  const [loadingPhotos, setLoadingPhotos] = useState(true)

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

  const loadSamplePhotos = async () => {
    try {
      setLoadingPhotos(true)
      // Try to get some recent photos to display
      const result = await photosApi.searchPhotos({
        search_type: 'processed',
        page: 1,
        page_size: 6,
      })
      setSamplePhotos(result.items || [])
    } catch (error) {
      console.error('Failed to load sample photos:', error)
      setSamplePhotos([])
    } finally {
      setLoadingPhotos(false)
    }
  }

  const getPhotoImageUrl = (photoId: number): string => {
    return `${apiClient.defaults.baseURL}/api/v1/photos/${photoId}/image`
  }

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section className="relative py-12 px-4 overflow-hidden" style={{ background: 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 50%, #f0f9ff 100%)' }}>
        <div className="max-w-6xl mx-auto relative z-10">
          <div className="text-center mb-8">
            <h1 className="text-4xl md:text-5xl font-bold mb-4 leading-tight" style={{ color: '#F97316' }}>
              Welcome to PunimTag
            </h1>
            <p className="text-xl md:text-2xl mb-3" style={{ color: '#2563EB' }}>
              Your Intelligent Photo Management System
            </p>
            <p className="text-lg max-w-2xl mx-auto text-gray-600">
              Organize, identify, and search through your photo collection like never before.
            </p>
          </div>
        </div>
      </section>

      {/* Feature Showcase 1 - AI Recognition */}
      <section className="py-16 px-4 bg-white">
        <div className="max-w-6xl mx-auto">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div>
              <div className="text-5xl mb-4">🤖</div>
              <h2 className="text-4xl font-bold text-gray-900 mb-4">
                Recognize Faces Automatically
              </h2>
              <p className="text-lg text-gray-600 mb-6">
                Never lose track of who's in your photos again. Our smart system
                automatically finds and recognizes faces in all your pictures. Just
                tell it who someone is once, and it will find them in thousands of
                photos—even from years ago.
              </p>
              <ul className="space-y-3 text-gray-700">
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Automatically finds faces in all your photos</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Recognizes the same person across different photos</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Works even with photos taken years apart</span>
                </li>
              </ul>
            </div>
            <div className="relative">
              <div className="bg-gray-50 rounded-2xl p-8 shadow-xl">
                <div className="aspect-video bg-white rounded-lg shadow-lg flex items-center justify-center">
                  <div className="text-center">
                    <div className="text-6xl mb-4">👥</div>
                    <p className="text-gray-500 text-sm">
                      Face recognition in action
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Feature Showcase 2 - Smart Search */}
      <section className="py-16 px-4 bg-gray-50">
        <div className="max-w-6xl mx-auto">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div className="order-2 md:order-1 relative">
              <div className="bg-gray-50 rounded-2xl p-8 shadow-xl">
                <div className="aspect-video bg-white rounded-lg shadow-lg flex items-center justify-center">
                  <div className="text-center">
                    <div className="text-6xl mb-4">🔍</div>
                    <p className="text-gray-500 text-sm">
                      Powerful search interface
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div className="order-1 md:order-2">
              <div className="text-5xl mb-4">🔍</div>
              <h2 className="text-4xl font-bold text-gray-900 mb-4">
                Find Anything, Instantly
              </h2>
              <p className="text-lg text-gray-600 mb-6">
                Search your entire photo collection by people, dates, tags, or
                folders. Our advanced filtering system makes it easy to find
                exactly what you're looking for, no matter how large your
                collection grows.
              </p>
              <ul className="space-y-3 text-gray-700">
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Search by person name across all photos</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Filter by date ranges and folders</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Tag-based organization and filtering</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </section>

      {/* Feature Showcase 3 - Batch Processing */}
      <section className="py-16 px-4 bg-white">
        <div className="max-w-6xl mx-auto">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div>
              <div className="text-5xl mb-4">⚡</div>
              <h2 className="text-4xl font-bold text-gray-900 mb-4">
                Process Thousands at Once
              </h2>
              <p className="text-lg text-gray-600 mb-6">
                Don't let a large photo collection overwhelm you. Our batch
                processing system efficiently handles thousands of photos with
                real-time progress tracking. Watch as your photos are organized
                automatically.
              </p>
              <ul className="space-y-3 text-gray-700">
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Batch face detection and recognition</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Real-time progress updates</span>
                </li>
                <li className="flex items-start gap-3">
                  <span className="text-xl" style={{ color: '#2563EB' }}>✓</span>
                  <span>Background job processing</span>
                </li>
              </ul>
            </div>
            <div className="relative">
              <div className="bg-gray-50 rounded-2xl p-8 shadow-xl">
                <div className="aspect-video bg-white rounded-lg shadow-lg flex items-center justify-center">
                  <div className="text-center">
                    <div className="text-6xl mb-4">📊</div>
                    <p className="text-gray-500 text-sm">
                      Batch processing dashboard
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Visual Gallery Section */}
      <section className="py-16 px-4 bg-white">
        <div className="max-w-6xl mx-auto">
          <h2 className="text-4xl font-bold text-center text-gray-900 mb-4">
            Organize Your Memories
          </h2>
          <p className="text-center text-lg text-gray-600 mb-12 max-w-2xl mx-auto">
            Transform your photo collection into an organized, searchable library
            of memories. Find any moment, any person, any time.
          </p>
          {loadingPhotos ? (
            <div className="grid md:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => (
                <div
                  key={i}
                  className="bg-gray-50 rounded-xl p-6 shadow-md aspect-square flex items-center justify-center animate-pulse"
                >
                  <div className="text-center">
                    <div className="text-6xl mb-4">📸</div>
                    <p className="text-gray-500 text-sm">Loading...</p>
                  </div>
                </div>
              ))}
            </div>
          ) : samplePhotos.length > 0 ? (
            <div className="grid md:grid-cols-3 gap-6">
              {samplePhotos.slice(0, 6).map((photo) => (
                <div
                  key={photo.id}
                  className="bg-gray-50 rounded-xl p-2 shadow-md aspect-square overflow-hidden group hover:shadow-lg transition-shadow"
                >
                  <img
                    src={getPhotoImageUrl(photo.id)}
                    alt={photo.filename}
                    className="w-full h-full object-cover rounded-lg"
                    loading="lazy"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement
                      target.style.display = 'none'
                      const parent = target.parentElement
                      if (parent && !parent.querySelector('.error-fallback')) {
                        const fallback = document.createElement('div')
                        fallback.className =
                          'w-full h-full flex items-center justify-center error-fallback'
                        fallback.innerHTML =
                          '<div class="text-center"><div class="text-6xl mb-4">📸</div><p class="text-gray-500 text-sm">Photo</p></div>'
                        parent.appendChild(fallback)
                      }
                    }}
                  />
                </div>
              ))}
            </div>
          ) : (
            <div className="grid md:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => (
                <div
                  key={i}
                  className="bg-gray-50 rounded-xl p-6 shadow-md aspect-square flex items-center justify-center"
                >
                  <div className="text-center">
                    <div className="text-6xl mb-4">📸</div>
                    <p className="text-gray-500 text-sm">Your photos</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-20 px-4 bg-white">
        <div className="max-w-4xl mx-auto text-center">
          <h2 className="text-4xl md:text-5xl font-bold mb-6" style={{ color: '#F97316' }}>
            Ready to Get Started?
          </h2>
          <p className="text-xl mb-8 max-w-2xl mx-auto text-gray-600">
            Begin organizing your photo collection today. Use the navigation menu
            to explore all the powerful features PunimTag has to offer.
          </p>
          <div className="flex flex-wrap justify-center gap-4">
            <div className="border rounded-lg px-6 py-3 text-sm" style={{ borderColor: '#2563EB', color: '#2563EB' }}>
              <span className="font-semibold">🗂️</span> Scan Photos
            </div>
            <div className="border rounded-lg px-6 py-3 text-sm" style={{ borderColor: '#2563EB', color: '#2563EB' }}>
              <span className="font-semibold">⚙️</span> Process Faces
            </div>
            <div className="border rounded-lg px-6 py-3 text-sm" style={{ borderColor: '#2563EB', color: '#2563EB' }}>
              <span className="font-semibold">👤</span> Identify People
            </div>
            <div className="border rounded-lg px-6 py-3 text-sm" style={{ borderColor: '#2563EB', color: '#2563EB' }}>
              <span className="font-semibold">🤖</span> Auto-Match
            </div>
            <div className="border rounded-lg px-6 py-3 text-sm" style={{ borderColor: '#2563EB', color: '#2563EB' }}>
              <span className="font-semibold">🔍</span> Search Photos
            </div>
          </div>
        </div>
      </section>
    </div>
  )
}
