'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'

interface Buyer {
  id: number
  username: string
  email: string
  created_at?: string
  referral_count?: number
  hasWholesaleAccess?: boolean
  hasInnerCircleAccess?: boolean
}

export default function BuyersManagementPage() {
  const router = useRouter()
  const [buyers, setBuyers] = useState<Buyer[]>([])
  const [filteredBuyers, setFilteredBuyers] = useState<Buyer[]>([])
  const [loading, setLoading] = useState(true)
  const [authenticated, setAuthenticated] = useState(false)
  const [editingBuyer, setEditingBuyer] = useState<Buyer | null>(null)
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
  })
  const [filters, setFilters] = useState({
    wholesaleOnly: false,
    innerCircleOnly: false,
  })

  useEffect(() => {
    // Check authentication
    fetch('/api/admin/check')
      .then((res) => res.json())
      .then((data) => {
        if (data.authenticated) {
          setAuthenticated(true)
          fetchBuyers()
        } else {
          router.push('/admin/login')
        }
      })
      .catch(() => {
        router.push('/admin/login')
      })
  }, [router])

  const fetchBuyers = async () => {
    try {
      const response = await fetch('/api/buyers')
      if (response.ok) {
        const data = await response.json()
        const buyersList = Array.isArray(data) ? data : []
        setBuyers(buyersList)
        applyFilters(buyersList, filters)
      }
    } catch (error) {
      console.error('Error fetching buyers:', error)
    } finally {
      setLoading(false)
    }
  }

  const applyFilters = (buyersList: Buyer[], currentFilters: typeof filters) => {
    let filtered = [...buyersList]
    
    if (currentFilters.wholesaleOnly) {
      filtered = filtered.filter(buyer => buyer.hasWholesaleAccess)
    }
    
    if (currentFilters.innerCircleOnly) {
      filtered = filtered.filter(buyer => buyer.hasInnerCircleAccess)
    }
    
    setFilteredBuyers(filtered)
  }

  useEffect(() => {
    applyFilters(buyers, filters)
  }, [filters])

  const handleEdit = (buyer: Buyer) => {
    setEditingBuyer(buyer)
    setFormData({
      username: buyer.username,
      email: buyer.email,
      password: '',
    })
  }

  const handleSave = async () => {
    if (!editingBuyer) return

    try {
      const updateData: any = {}
      if (formData.username !== editingBuyer.username) {
        updateData.username = formData.username
      }
      if (formData.email !== editingBuyer.email) {
        updateData.email = formData.email
      }
      if (formData.password) {
        updateData.password = formData.password
      }

      if (Object.keys(updateData).length === 0) {
        setEditingBuyer(null)
        return
      }

      const response = await fetch(`/api/buyers/${editingBuyer.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updateData),
      })

      if (response.ok) {
        alert('Buyer updated successfully')
        setEditingBuyer(null)
        fetchBuyers()
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error updating buyer:', error)
      alert('Failed to update buyer')
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this buyer? This will also delete all their sales.')) {
      return
    }

    try {
      const response = await fetch(`/api/buyers/${id}`, {
        method: 'DELETE',
      })

      if (response.ok) {
        alert('Buyer deleted successfully')
        fetchBuyers()
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error deleting buyer:', error)
      alert('Failed to delete buyer')
    }
  }

  if (loading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'var(--bg)'
      }}>
        <p style={{ color: 'var(--muted)' }}>Loading...</p>
      </div>
    )
  }

  if (!authenticated) {
    return null
  }

  return (
    <div style={{
      minHeight: '100vh',
      background: 'var(--bg)',
      padding: '40px 20px'
    }}>
      <div className="container" style={{ maxWidth: '1200px', margin: '0 auto' }}>
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '30px'
        }}>
          <h1>Buyer Management</h1>
          <button
            onClick={() => router.push('/admin')}
            style={{
              padding: '10px 20px',
              background: 'transparent',
              border: '1px solid var(--border)',
              borderRadius: '8px',
              color: 'var(--text)',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            Back to Dashboard
          </button>
        </div>

        <div style={{
          marginBottom: '20px',
          padding: '16px',
          background: 'var(--card)',
          borderRadius: '8px',
          border: '1px solid var(--border)'
        }}>
          <h3 style={{ marginBottom: '12px', fontSize: '16px' }}>Filters</h3>
          <div style={{ display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
            <label style={{ 
              display: 'flex', 
              alignItems: 'center', 
              gap: '8px',
              cursor: 'pointer',
              userSelect: 'none'
            }}>
              <input
                type="checkbox"
                checked={filters.wholesaleOnly}
                onChange={(e) => setFilters({ ...filters, wholesaleOnly: e.target.checked })}
                style={{ width: '16px', height: '16px', cursor: 'pointer' }}
              />
              <span>Wholesale Access (3+ referrals)</span>
            </label>
            <label style={{ 
              display: 'flex', 
              alignItems: 'center', 
              gap: '8px',
              cursor: 'pointer',
              userSelect: 'none'
            }}>
              <input
                type="checkbox"
                checked={filters.innerCircleOnly}
                onChange={(e) => setFilters({ ...filters, innerCircleOnly: e.target.checked })}
                style={{ width: '16px', height: '16px', cursor: 'pointer' }}
              />
              <span>Inner Circle Access (10+ referrals)</span>
            </label>
          </div>
          {(filters.wholesaleOnly || filters.innerCircleOnly) && (
            <p style={{ 
              marginTop: '12px', 
              color: 'var(--muted)', 
              fontSize: '14px' 
            }}>
              Showing {filteredBuyers.length} of {buyers.length} buyers
            </p>
          )}
        </div>

        {(filters.wholesaleOnly || filters.innerCircleOnly ? filteredBuyers : buyers).length === 0 ? (
          <p style={{ color: 'var(--muted)' }}>No buyers found</p>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {(filters.wholesaleOnly || filters.innerCircleOnly ? filteredBuyers : buyers).map((buyer) => (
              <div
                key={buyer.id}
                className="drop-card"
                style={{
                  background: editingBuyer?.id === buyer.id ? 'var(--bg-soft)' : 'var(--card)',
                  padding: '20px'
                }}
              >
                {editingBuyer?.id === buyer.id ? (
                  <div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
                      <div>
                        <label style={{ display: 'block', marginBottom: '8px' }}>Username</label>
                        <input
                          type="text"
                          value={formData.username}
                          onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                          style={{
                            width: '100%',
                            padding: '8px',
                            borderRadius: '8px',
                            border: '1px solid var(--border)',
                            background: 'var(--bg-soft)',
                            color: 'var(--text)'
                          }}
                        />
                      </div>
                      <div>
                        <label style={{ display: 'block', marginBottom: '8px' }}>Email</label>
                        <input
                          type="email"
                          value={formData.email}
                          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                          style={{
                            width: '100%',
                            padding: '8px',
                            borderRadius: '8px',
                            border: '1px solid var(--border)',
                            background: 'var(--bg-soft)',
                            color: 'var(--text)'
                          }}
                        />
                      </div>
                      <div>
                        <label style={{ display: 'block', marginBottom: '8px' }}>New Password (leave empty to keep current)</label>
                        <input
                          type="password"
                          value={formData.password}
                          onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                          style={{
                            width: '100%',
                            padding: '8px',
                            borderRadius: '8px',
                            border: '1px solid var(--border)',
                            background: 'var(--bg-soft)',
                            color: 'var(--text)'
                          }}
                        />
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button
                        onClick={handleSave}
                        className="cta"
                        style={{ padding: '8px 16px', fontSize: '14px' }}
                      >
                        Save
                      </button>
                      <button
                        onClick={() => setEditingBuyer(null)}
                        style={{
                          padding: '8px 16px',
                          fontSize: '14px',
                          background: 'transparent',
                          border: '1px solid var(--border)',
                          borderRadius: '8px',
                          color: 'var(--text)',
                          cursor: 'pointer'
                        }}
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                ) : (
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div style={{ flex: 1 }}>
                      <h3 style={{ marginBottom: '8px' }}>{buyer.username}</h3>
                      <p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
                        Email: {buyer.email}
                      </p>
                      <p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
                        ID: {buyer.id}
                      </p>
                      {buyer.created_at && (
                        <p style={{ color: 'var(--muted)', fontSize: '12px', marginBottom: '4px' }}>
                          Created: {new Date(buyer.created_at).toLocaleString()}
                        </p>
                      )}
                      <div style={{ 
                        display: 'flex', 
                        gap: '8px', 
                        marginTop: '8px',
                        flexWrap: 'wrap'
                      }}>
                        <span style={{ 
                          padding: '4px 8px',
                          borderRadius: '4px',
                          fontSize: '12px',
                          background: buyer.hasWholesaleAccess ? '#10b981' : '#6b7280',
                          color: '#fff'
                        }}>
                          {buyer.referral_count || 0} referrals - Wholesale {buyer.hasWholesaleAccess ? '✓' : '✗'}
                        </span>
                        <span style={{ 
                          padding: '4px 8px',
                          borderRadius: '4px',
                          fontSize: '12px',
                          background: buyer.hasInnerCircleAccess ? '#8b5cf6' : '#6b7280',
                          color: '#fff'
                        }}>
                          Inner Circle {buyer.hasInnerCircleAccess ? '✓' : '✗'}
                        </span>
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button
                        onClick={() => handleEdit(buyer)}
                        style={{
                          padding: '6px 12px',
                          fontSize: '12px',
                          background: 'transparent',
                          border: '1px solid var(--border)',
                          borderRadius: '6px',
                          color: 'var(--text)',
                          cursor: 'pointer'
                        }}
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => handleDelete(buyer.id)}
                        style={{
                          padding: '6px 12px',
                          fontSize: '12px',
                          background: '#dc2626',
                          border: 'none',
                          borderRadius: '6px',
                          color: '#fff',
                          cursor: 'pointer'
                        }}
                      >
                        Delete
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

