'use client'

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

interface Sale {
  id: number
  drop_id: number
  buyer_id: number
  size: number
  payment_id: string | null
  created_at: string
  drop_item?: string
  drop_unit?: string
  drop_ppu?: number
  buyer_username?: string
  buyer_email?: string
  buyer_fullname?: string
  buyer_address?: string
  buyer_phone?: string
}

export default function SalesManagementPage() {
  const router = useRouter()
  const [sales, setSales] = useState<Sale[]>([])
  const [loading, setLoading] = useState(true)
  const [authenticated, setAuthenticated] = useState(false)
  const [editingSale, setEditingSale] = useState<Sale | null>(null)
  const [formData, setFormData] = useState({
    drop_id: '',
    buyer_id: '',
    size: '',
    payment_id: '',
  })

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

  const fetchSales = async () => {
    try {
      const response = await fetch('/api/sales/list')
      if (response.ok) {
        const data = await response.json()
        setSales(Array.isArray(data) ? data : [])
      }
    } catch (error) {
      console.error('Error fetching sales:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleEdit = (sale: Sale) => {
    setEditingSale(sale)
    setFormData({
      drop_id: sale.drop_id.toString(),
      buyer_id: sale.buyer_id.toString(),
      size: sale.size.toString(),
      payment_id: sale.payment_id || '',
    })
  }

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

    try {
      const updateData: any = {}
      if (parseInt(formData.drop_id) !== editingSale.drop_id) {
        updateData.drop_id = parseInt(formData.drop_id)
      }
      if (parseInt(formData.buyer_id) !== editingSale.buyer_id) {
        updateData.buyer_id = parseInt(formData.buyer_id)
      }
      if (parseInt(formData.size) !== editingSale.size) {
        updateData.size = parseInt(formData.size)
      }
      if (formData.payment_id !== (editingSale.payment_id || '')) {
        updateData.payment_id = formData.payment_id || null
      }

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

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

      if (response.ok) {
        alert('Sale updated successfully')
        setEditingSale(null)
        fetchSales()
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error updating sale:', error)
      alert('Failed to update sale')
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this sale?')) {
      return
    }

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

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

  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>Sales 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>

        {sales.length === 0 ? (
          <p style={{ color: 'var(--muted)' }}>No sales found</p>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {sales.map((sale) => (
              <div
                key={sale.id}
                className="drop-card"
                style={{
                  background: editingSale?.id === sale.id ? 'var(--bg-soft)' : 'var(--card)',
                  padding: '20px'
                }}
              >
                {editingSale?.id === sale.id ? (
                  <div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
                      <div>
                        <label style={{ display: 'block', marginBottom: '8px' }}>Drop ID</label>
                        <input
                          type="number"
                          value={formData.drop_id}
                          onChange={(e) => setFormData({ ...formData, drop_id: 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' }}>Buyer ID</label>
                        <input
                          type="number"
                          value={formData.buyer_id}
                          onChange={(e) => setFormData({ ...formData, buyer_id: 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' }}>Size (grams)</label>
                        <input
                          type="number"
                          value={formData.size}
                          onChange={(e) => setFormData({ ...formData, size: 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' }}>Payment ID</label>
                        <input
                          type="text"
                          value={formData.payment_id}
                          onChange={(e) => setFormData({ ...formData, payment_id: 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={() => setEditingSale(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' }}>Sale #{sale.id}</h3>
                      <p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
                        Drop: {sale.drop_item || `#${sale.drop_id}`} · Size: {sale.size}g
                      </p>
                      <p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
                        Buyer: {sale.buyer_username || `#${sale.buyer_id}`} ({sale.buyer_email || 'N/A'})
                      </p>
                      {(sale.buyer_fullname || sale.buyer_address || sale.buyer_phone) && (
                        <div style={{ 
                          background: 'var(--bg-soft)', 
                          padding: '12px', 
                          borderRadius: '8px', 
                          marginTop: '8px',
                          marginBottom: '8px'
                        }}>
                          <p style={{ color: 'var(--text)', fontSize: '13px', fontWeight: '600', marginBottom: '6px' }}>
                            Delivery Information:
                          </p>
                          {sale.buyer_fullname && (
                            <p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
                              Name: {sale.buyer_fullname}
                            </p>
                          )}
                          {sale.buyer_address && (
                            <p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
                              Address: {sale.buyer_address}
                            </p>
                          )}
                          {sale.buyer_phone && (
                            <p style={{ color: 'var(--muted)', fontSize: '13px', marginBottom: '4px' }}>
                              Phone: {sale.buyer_phone}
                            </p>
                          )}
                        </div>
                      )}
                      {sale.drop_ppu && (
                        <p style={{ color: 'var(--muted)', fontSize: '14px', marginBottom: '4px' }}>
                          Price: {((sale.drop_ppu / 1000) * sale.size).toFixed(2)} CHF
                        </p>
                      )}
                      <p style={{ color: 'var(--muted)', fontSize: '12px' }}>
                        Created: {new Date(sale.created_at).toLocaleString()}
                        {sale.payment_id && ` · Payment: ${sale.payment_id}`}
                      </p>
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button
                        onClick={() => handleEdit(sale)}
                        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(sale.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>
  )
}

