'use client'

import { useState, useEffect } from 'react'
import { Plus, Search, Edit, Trash2, ExternalLink, ToggleLeft, ToggleRight, Facebook, Instagram, Twitter, Youtube, MessageCircle } from 'lucide-react'
import Link from 'next/link'
import { AdminSidebar } from '@/components/admin-sidebar'
import { useAdminAuth } from '@/hooks/useAdminAuth'
import { useRouter } from 'next/navigation'

interface SocialMedia {
  id: string
  platform: string
  name: string
  url: string
  username?: string
  description?: string
  icon?: string
  isActive: boolean
  order: number
  createdAt: string
  updatedAt: string
}

const platformIcons: { [key: string]: React.ReactNode } = {
  FACEBOOK: <Facebook className="w-5 h-5 text-blue-600" />,
  INSTAGRAM: <Instagram className="w-5 h-5 text-pink-600" />,
  TWITTER: <Twitter className="w-5 h-5 text-black" />,
  YOUTUBE: <Youtube className="w-5 h-5 text-red-600" />,
  TIKTOK: <MessageCircle className="w-5 h-5 text-black" />,
  LINKEDIN: <ExternalLink className="w-5 h-5 text-blue-700" />,
  WHATSAPP: <MessageCircle className="w-5 h-5 text-green-600" />,
  TELEGRAM: <MessageCircle className="w-5 h-5 text-blue-500" />
}

const platformColors: { [key: string]: string } = {
  FACEBOOK: 'bg-blue-100 text-blue-700 border-blue-300',
  INSTAGRAM: 'bg-pink-100 text-pink-700 border-pink-300',
  TWITTER: 'bg-gray-100 text-gray-700 border-gray-300',
  YOUTUBE: 'bg-red-100 text-red-700 border-red-300',
  TIKTOK: 'bg-gray-100 text-gray-700 border-gray-300',
  LINKEDIN: 'bg-blue-100 text-blue-700 border-blue-300',
  WHATSAPP: 'bg-green-100 text-green-700 border-green-300',
  TELEGRAM: 'bg-blue-100 text-blue-700 border-blue-300'
}

export default function SocialMediaManagement() {
  const router = useRouter()
  const { user, loading, isAuthenticated, logout, getAuthHeaders } = useAdminAuth()
  const [socialMediaList, setSocialMediaList] = useState<SocialMedia[]>([])
  const [loadingData, setLoadingData] = useState(true)
  const [search, setSearch] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [showActiveOnly, setShowActiveOnly] = useState(false)
  const [selectedPlatform, setSelectedPlatform] = useState('')

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.push('/admin/login')
      return
    }

    if (isAuthenticated) {
      fetchSocialMedia()
    }
  }, [loading, isAuthenticated, router])

  const fetchSocialMedia = async () => {
    try {
      setLoadingData(true)
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: '10',
        search,
        ...(showActiveOnly && { isActive: 'true' }),
        ...(selectedPlatform && { platform: selectedPlatform })
      })

      const response = await fetch(`/api/admin/social-media?${params}`, {
        headers: getAuthHeaders()
      })
      const result = await response.json()

      if (result.success) {
        setSocialMediaList(result.data)
        setTotalPages(result.pagination.pages)
      } else {
        console.error('Failed to fetch social media:', result.message)
      }
    } catch (error) {
      console.error('Error fetching social media:', error)
    } finally {
      setLoadingData(false)
    }
  }

  const toggleStatus = async (id: string, currentStatus: boolean) => {
    try {
      const response = await fetch(`/api/admin/social-media/${id}`, {
        method: 'PUT',
        headers: getAuthHeaders('json'),
        body: JSON.stringify({
          isActive: !currentStatus
        })
      })

      const result = await response.json()
      if (result.success) {
        fetchSocialMedia()
      } else {
        console.error('Failed to toggle status:', result.message)
      }
    } catch (error) {
      console.error('Error toggling status:', error)
    }
  }

  const deleteSocialMedia = async (id: string) => {
    if (!confirm('Are you sure you want to delete this social media account? This action cannot be undone.')) {
      return
    }

    try {
      const response = await fetch(`/api/admin/social-media/${id}`, {
        method: 'DELETE',
        headers: getAuthHeaders('json')
      })

      const result = await response.json()
      if (result.success) {
        fetchSocialMedia()
      } else {
        console.error('Failed to delete social media:', result.message)
      }
    } catch (error) {
      console.error('Error deleting social media:', error)
    }
  }

  useEffect(() => {
    if (isAuthenticated) {
      fetchSocialMedia()
    }
  }, [currentPage, search, showActiveOnly, selectedPlatform, isAuthenticated])

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">Loading...</p>
        </div>
      </div>
    )
  }

  return (
    <AdminSidebar user={user}>
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Social Media Management</h1>
          <p className="text-gray-600">Manage social media accounts and links</p>
        </div>
        <Link
          href="/admin/social-media/create"
          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
        >
          <Plus className="w-5 h-5" />
          Add Social Media
        </Link>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                placeholder="Search by name, username, or description..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>
          <div className="flex items-center gap-2">
            <select
              value={selectedPlatform}
              onChange={(e) => setSelectedPlatform(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">All Platforms</option>
              <option value="FACEBOOK">Facebook</option>
              <option value="INSTAGRAM">Instagram</option>
              <option value="TWITTER">Twitter</option>
              <option value="YOUTUBE">YouTube</option>
              <option value="TIKTOK">TikTok</option>
              <option value="LINKEDIN">LinkedIn</option>
              <option value="WHATSAPP">WhatsApp</option>
              <option value="TELEGRAM">Telegram</option>
            </select>
            <button
              onClick={() => setShowActiveOnly(!showActiveOnly)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                showActiveOnly 
                  ? 'bg-green-100 text-green-700 border border-green-300' 
                  : 'bg-gray-100 text-gray-700 border border-gray-300'
              }`}
            >
              {showActiveOnly ? <ToggleRight className="w-5 h-5" /> : <ToggleLeft className="w-5 h-5" />}
              Active Only
            </button>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        {loadingData ? (
          <div className="p-8 text-center">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p className="mt-2 text-gray-600">Loading...</p>
          </div>
        ) : socialMediaList.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            <MessageCircle className="w-12 h-12 mx-auto mb-4 text-gray-300" />
            <p>No social media accounts found</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Platform
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Account
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    URL
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Description
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Status
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {socialMediaList.map((socialMedia) => (
                  <tr key={socialMedia.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        {platformIcons[socialMedia.platform]}
                        <span className={`px-2 py-1 rounded-full text-xs font-medium border ${platformColors[socialMedia.platform]}`}>
                          {socialMedia.platform}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div>
                        <div className="text-sm font-medium text-gray-900">{socialMedia.name}</div>
                        {socialMedia.username && (
                          <div className="text-sm text-gray-500">@{socialMedia.username}</div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <a
                          href={socialMedia.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 text-sm truncate max-w-xs"
                        >
                          {socialMedia.url}
                        </a>
                        <ExternalLink className="w-4 h-4 text-gray-400 flex-shrink-0" />
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-600 max-w-xs truncate">
                        {socialMedia.description || '-'}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <button
                        onClick={() => toggleStatus(socialMedia.id, socialMedia.isActive)}
                        className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium transition-colors ${
                          socialMedia.isActive
                            ? 'bg-green-100 text-green-700'
                            : 'bg-red-100 text-red-700'
                        }`}
                      >
                        {socialMedia.isActive ? 'Active' : 'Inactive'}
                      </button>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <Link
                          href={`/admin/social-media/${socialMedia.id}/edit`}
                          className="text-blue-600 hover:text-blue-800"
                        >
                          <Edit className="w-4 h-4" />
                        </Link>
                        <button
                          onClick={() => deleteSocialMedia(socialMedia.id)}
                          className="text-red-600 hover:text-red-800"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex justify-center items-center gap-2 mt-6">
          <button
            onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
            disabled={currentPage === 1}
            className="px-3 py-1 rounded-lg border border-gray-300 text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            Previous
          </button>
          <span className="text-sm text-gray-600">
            Page {currentPage} of {totalPages}
          </span>
          <button
            onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
            disabled={currentPage === totalPages}
            className="px-3 py-1 rounded-lg border border-gray-300 text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            Next
          </button>
        </div>
      )}
    </AdminSidebar>
  )
}