'use client'

import { useState, useEffect } from 'react'
import { LabelProfileForm, LabelProfileFormData } from '@/components/LabelProfileForm'

export default function LabelSettingsPage() {
  const [label, setLabel] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [isUpdating, setIsUpdating] = useState(false)

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

  const fetchLabel = async () => {
    try {
      // Check authentication
      const userRes = await fetch('/api/users/me')
      if (!userRes.ok) {
        window.location.href = '/login'
        return
      }
      const userData = await userRes.json()

      // Fetch user's label
      const labelRes = await fetch(`/api/users/${userData.user.id}/label`)
      if (!labelRes.ok) {
        window.location.href = '/label/create'
        return
      }
      const labelData = await labelRes.json()
      setLabel(labelData.label)
    } catch (error) {
      console.error('Failed to fetch label:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async (data: LabelProfileFormData) => {
    setIsUpdating(true)
    try {
      const res = await fetch(`/api/labels/${label.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      })

      if (res.ok) {
        const result = await res.json()
        setLabel(result.label)
        alert('Label profile updated successfully')
      } else {
        const error = await res.json()
        alert(error.error || 'Failed to update label')
      }
    } catch (error) {
      console.error('Failed to update label:', error)
      alert('Network error')
    } finally {
      setIsUpdating(false)
    }
  }

  const handleCancel = () => {
    window.location.href = '/label/dashboard'
  }

  if (loading) {
    return (
      <main className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <p className="text-zinc-400">Loading settings...</p>
      </main>
    )
  }

  if (!label) {
    return (
      <main className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-zinc-400 mb-4">Label not found</p>
          <a
            href="/label/dashboard"
            className="px-6 py-3 bg-purple-600 hover:bg-purple-700 text-white font-semibold rounded-lg inline-block"
          >
            Go to Dashboard
          </a>
        </div>
      </main>
    )
  }

  return (
    <main className="min-h-screen bg-zinc-950">
      <div className="max-w-4xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-white mb-4">Label Settings</h1>
          <p className="text-xl text-zinc-400">
            Manage your label profile and information
          </p>
        </div>

        {/* Profile Form */}
        <div className="bg-zinc-900 rounded-lg p-8">
          <h2 className="text-2xl font-semibold text-white mb-6">Profile Information</h2>
          <LabelProfileForm
            label={{
              name: label.name,
              description: label.description,
              logoUrl: label.logoUrl,
              website: label.website
            }}
            onSave={handleSave}
            onCancel={handleCancel}
            isLoading={isUpdating}
          />
        </div>

        {/* Danger Zone */}
        <div className="bg-zinc-900 rounded-lg p-8 mt-6 border border-red-900/50">
          <h2 className="text-2xl font-semibold text-white mb-4">Danger Zone</h2>
          <p className="text-zinc-400 mb-4">
            Once you delete your label, all associated data will be permanently removed. Artists will be unlinked. This action cannot be undone.
          </p>
          <button className="px-6 py-3 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg transition-colors">
            Delete Label
          </button>
        </div>
      </div>
    </main>
  )
}
