'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, Upload, X } from 'lucide-react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { AdminSidebar } from '@/components/admin-sidebar'
import { useAdminAuth } from '@/hooks/useAdminAuth'
import { useToast } from '@/components/ui/use-toast'

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

export default function EditSocialMedia() {
  const router = useRouter()
  const params = useParams()
  const { user, loading, isAuthenticated, logout, getAuthHeaders } = useAdminAuth()
  const { toast } = useToast()
  const [submitting, setSubmitting] = useState(false)
  const [fetchLoading, setFetchLoading] = useState(true)
  const [socialMedia, setSocialMedia] = useState<SocialMedia | null>(null)
  const [formData, setFormData] = useState({
    platform: '',
    name: '',
    url: '',
    username: '',
    description: '',
    isActive: true,
    order: 0
  })
  const [iconPreview, setIconPreview] = useState<string | null>(null)

  const platforms = [
    { value: 'FACEBOOK', label: 'Facebook', color: 'text-blue-600' },
    { value: 'INSTAGRAM', label: 'Instagram', color: 'text-pink-600' },
    { value: 'TWITTER', label: 'Twitter', color: 'text-black' },
    { value: 'YOUTUBE', label: 'YouTube', color: 'text-red-600' },
    { value: 'TIKTOK', label: 'TikTok', color: 'text-black' },
    { value: 'LINKEDIN', label: 'LinkedIn', color: 'text-blue-700' },
    { value: 'WHATSAPP', label: 'WhatsApp', color: 'text-green-600' },
    { value: 'TELEGRAM', label: 'Telegram', color: 'text-blue-500' }
  ]

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

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

  const fetchSocialMedia = async () => {
    try {
      const response = await fetch(`/api/admin/social-media/${params.id}`, {
        headers: getAuthHeaders('json')
      })
      const result = await response.json()

      if (result.success) {
        const socialMediaData = result.data
        setSocialMedia(socialMediaData)
        setFormData({
          platform: socialMediaData.platform || '',
          name: socialMediaData.name || '',
          url: socialMediaData.url || '',
          username: socialMediaData.username || '',
          description: socialMediaData.description || '',
          isActive: socialMediaData.isActive,
          order: socialMediaData.order || 0
        })
        setIconPreview(socialMediaData.icon)
      } else {
        toast({
          title: 'Error',
          description: `Gagal memuat data social media: ${result.message}`,
          variant: 'destructive'
        })
        router.push('/admin/social-media')
      }
    } catch (error) {
      console.error('Error fetching social media:', error)
      toast({
        title: 'Error',
        description: 'Gagal memuat data social media. Silakan coba lagi.',
        variant: 'destructive'
      })
      router.push('/admin/social-media')
    } finally {
      setFetchLoading(false)
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
    }))
  }

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onloadend = () => {
        setIconPreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const removeIcon = () => {
    setIconPreview(null)
    const iconInput = document.getElementById('icon') as HTMLInputElement
    if (iconInput) iconInput.value = ''
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.platform || !formData.name || !formData.url) {
      toast({
        title: 'Validasi Gagal',
        description: 'Platform, nama, dan URL wajib diisi',
        variant: 'destructive'
      })
      return
    }

    setSubmitting(true)

    try {
      const formDataToSend = new FormData()
      
      Object.entries(formData).forEach(([key, value]) => {
        if (typeof value === 'boolean') {
          formDataToSend.append(key, value.toString())
        } else {
          formDataToSend.append(key, value)
        }
      })

      const iconInput = document.getElementById('icon') as HTMLInputElement

      if (iconInput?.files?.[0]) {
        formDataToSend.append('icon', iconInput.files[0])
      }

      const response = await fetch(`/api/admin/social-media/${params.id}`, {
        method: 'PUT',
        headers: getAuthHeaders('formData'),
        body: formDataToSend
      })

      const result = await response.json()

      if (result.success) {
        toast({
          title: 'Berhasil',
          description: 'Akun social media berhasil diperbarui',
          variant: 'success'
        })
        router.push('/admin/social-media')
      } else {
        toast({
          title: 'Gagal',
          description: result.message || 'Terjadi kesalahan saat memperbarui social media',
          variant: 'destructive'
        })
      }
    } catch (error) {
      console.error('Error updating social media:', error)
      toast({
        title: 'Error',
        description: 'Terjadi kesalahan saat memperbarui social media. Silakan coba lagi.',
        variant: 'destructive'
      })
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <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">Memuat...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  if (!loading && !isAuthenticated) {
    return null // Will redirect
  }

  if (fetchLoading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <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">Memuat data social media...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  if (!socialMedia) {
    return (
      <AdminSidebar user={user}>
        <div className="text-center text-gray-500 py-12">
          <p>Social media account not found</p>
        </div>
      </AdminSidebar>
    )
  }

  return (
    <AdminSidebar user={user}>
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Link
              href="/admin/social-media"
              className="flex items-center gap-2 text-gray-600 hover:text-gray-900"
            >
              <ArrowLeft className="w-4 h-4" />
              Kembali ke Social Media
            </Link>
          </div>
          <h2 className="text-2xl font-bold text-gray-900">Edit Social Media Account</h2>
          <p className="text-gray-600">Perbarui informasi akun social media</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Informasi Dasar</CardTitle>
            <CardDescription>
              Atur informasi utama akun social media
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="platform">Platform *</Label>
                <Select
                  value={formData.platform}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, platform: value }))}
                  required
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih platform" />
                  </SelectTrigger>
                  <SelectContent>
                    {platforms.map((platform) => (
                      <SelectItem key={platform.value} value={platform.value}>
                        {platform.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="name">Nama Tampilan *</Label>
                <Input
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  required
                  placeholder="contoh: Polres Wonosobo Official"
                />
              </div>

              <div className="md:col-span-2">
                <Label htmlFor="url">URL *</Label>
                <Input
                  id="url"
                  name="url"
                  type="url"
                  value={formData.url}
                  onChange={handleInputChange}
                  required
                  placeholder="https://facebook.com/polreswonosobo"
                />
              </div>

              <div>
                <Label htmlFor="username">Username/Handle</Label>
                <Input
                  id="username"
                  name="username"
                  value={formData.username}
                  onChange={handleInputChange}
                  placeholder="@polreswonosobo"
                />
              </div>

              <div>
                <Label htmlFor="order">Urutan</Label>
                <Input
                  id="order"
                  name="order"
                  type="number"
                  value={formData.order}
                  onChange={handleInputChange}
                  placeholder="Urutan tampilan"
                />
              </div>

              <div className="md:col-span-2">
                <Label htmlFor="description">Deskripsi</Label>
                <Textarea
                  id="description"
                  name="description"
                  value={formData.description}
                  onChange={handleInputChange}
                  rows={3}
                  placeholder="Deskripsi singkat tentang akun social media ini"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Icon Kustom (Opsional)</CardTitle>
            <CardDescription>
              Upload icon kustom untuk platform social media. Jika tidak diisi, akan menggunakan icon default.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="max-w-md">
              <div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-gray-400 transition-colors">
                <div className="space-y-1 text-center">
                  {iconPreview ? (
                    <div className="relative">
                      <img
                        src={iconPreview}
                        alt="Icon preview"
                        className="mx-auto h-24 w-24 object-contain"
                      />
                      <button
                        type="button"
                        onClick={removeIcon}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  ) : (
                    <Upload className="mx-auto h-12 w-12 text-gray-400" />
                  )}
                  <div className="flex text-sm text-gray-600">
                    <label
                      htmlFor="icon"
                      className="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-blue-500"
                    >
                      <span>Upload icon</span>
                      <input
                        id="icon"
                        name="icon"
                        type="file"
                        accept="image/*"
                        onChange={handleFileChange}
                        className="sr-only"
                      />
                    </label>
                    <p className="pl-1">atau drag and drop</p>
                  </div>
                  <p className="text-xs text-gray-500">PNG, JPG, SVG hingga 5MB (opsional)</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center">
              <input
                type="checkbox"
                name="isActive"
                id="isActive"
                checked={formData.isActive}
                onChange={handleInputChange}
                className="h-4 w-4 text-amber-600 focus:ring-amber-500 border-gray-300 rounded"
              />
              <Label htmlFor="isActive" className="ml-2 block text-sm text-gray-900">
                Aktif (terlihat di website)
              </Label>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end gap-4">
          <Link
            href="/admin/social-media"
          >
            <Button variant="outline" type="button">
              Batal
            </Button>
          </Link>
          <Button
            type="submit"
            disabled={submitting}
            className="bg-amber-600 hover:bg-amber-700"
          >
            <Save className="w-4 h-4 mr-2" />
            {submitting ? 'Memperbarui...' : 'Perbarui Social Media'}
          </Button>
        </div>
      </form>
    </AdminSidebar>
  )
}