import { useState, useEffect } from 'react'
import { Modal } from './ui/modal'
import { apiClient } from '../api/client'
import { useSettings } from '../context/SettingsContext'
import Label from './form/Label'

interface QuickMetalModalProps {
  isOpen: boolean
  onClose: () => void
  orderId: number
  orderNumber: string
  customerId?: number
  onSuccess?: () => void
}

const statusOptions = [
  { value: 'IN_PROGRESS', label: 'در حال پردازش' },
  { value: 'WEIGHED', label: 'وزن‌کشی شده' },
  { value: 'DELIVERED_RECEIVED', label: 'تحویل/دریافت داده شده' },
]

interface MetalRemaining {
  product_id: number
  product: {
    id: number
    name: string
    metal_type: string
    purity: number
  } | null
  line_grams: number
  transacted_grams: number
  remaining_grams: number
}

export const QuickMetalModal = ({
  isOpen,
  onClose,
  orderId,
  orderNumber,
  customerId,
  onSuccess,
}: QuickMetalModalProps) => {
  const [loading, setLoading] = useState(false)
  const [loadingBalance, setLoadingBalance] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  
  const [productId, setProductId] = useState<string>('')
  const [grams, setGrams] = useState<string>('')
  const [status, setStatus] = useState('IN_PROGRESS')
  const [notes, setNotes] = useState('')
  
  const [metalRemaining, setMetalRemaining] = useState<MetalRemaining[]>([])

  useEffect(() => {
    if (isOpen && orderId) {
      loadRemainingBalance()
    }
  }, [isOpen, orderId])

  const loadRemainingBalance = async () => {
    if (!orderId) return
    setLoadingBalance(true)
    try {
      const res = await apiClient.get(`/orders/${orderId}/remaining-balances`)
      const data = res?.data ?? res
      setMetalRemaining(data.metal || [])
      
      // Pre-select first remaining metal
      if (data.metal && data.metal.length > 0) {
        const first = data.metal[0]
        setProductId(String(first.product_id))
        setGrams(String(first.remaining_grams))
      }
    } catch {
      // Ignore errors
    } finally {
      setLoadingBalance(false)
    }
  }

  const handleProductChange = (productIdValue: string) => {
    setProductId(productIdValue)
    const selected = metalRemaining.find(m => String(m.product_id) === productIdValue)
    if (selected) {
      setGrams(String(selected.remaining_grams))
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setSuccess(null)
    setLoading(true)
    
    try {
      const gramsNum = parseFloat(grams) || 0
      if (!productId) {
        setError('لطفا محصول را انتخاب کنید')
        setLoading(false)
        return
      }
      if (gramsNum < 0.001) {
        setError('وزن باید حداقل ۰.۰۰۱ گرم باشد')
        setLoading(false)
        return
      }
      
      const payload = {
        order_id: orderId,
        product_id: Number(productId),
        grams: gramsNum,
        status,
        notes: notes.trim() || undefined,
      }
      
      await apiClient.post('/metals', payload)
      setSuccess('فلز با موفقیت ثبت شد')
      
      setTimeout(() => {
        onSuccess?.()
        handleClose()
      }, 1000)
    } catch (err: any) {
      const msg = err.response?.data?.message || 'خطا در ثبت فلز'
      const validationErrors = err.response?.data?.errors
      setError(validationErrors ? `${msg}: ${Object.values(validationErrors).flat().join('، ')}` : msg)
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    setError(null)
    setSuccess(null)
    setProductId('')
    setGrams('')
    setStatus('IN_PROGRESS')
    setNotes('')
    setMetalRemaining([])
    onClose()
  }

  return (
    <Modal isOpen={isOpen} onClose={handleClose} className="max-w-2xl m-4">
      <div className="relative w-full p-6 overflow-y-auto bg-white rounded-3xl dark:bg-gray-900">
        <div className="mb-6">
          <h3 className="text-xl font-semibold text-gray-800 dark:text-white/90">
            ثبت سریع تراکنش فلز
          </h3>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            سفارش: {orderNumber}
          </p>
        </div>

        {error && (
          <div className="mb-4 rounded-lg border border-error-200 bg-error-50 p-4 dark:border-error-500/20 dark:bg-error-500/10">
            <p className="text-sm text-error-600 dark:text-error-400">{error}</p>
          </div>
        )}
        {success && (
          <div className="mb-4 rounded-lg border border-success-200 bg-success-50 p-4 dark:border-success-500/20 dark:bg-success-500/10">
            <p className="text-sm text-success-600 dark:text-success-400">{success}</p>
          </div>
        )}

        {loadingBalance ? (
          <div className="flex items-center justify-center py-8">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-brand-500 border-t-transparent"></div>
          </div>
        ) : metalRemaining.length === 0 ? (
          <div className="mb-4 rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/50">
            <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
              تمام فلزات این سفارش ثبت شده‌اند.
            </p>
          </div>
        ) : (
          <>
            {metalRemaining.length > 0 && (
              <div className="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-500/20 dark:bg-blue-500/10">
                <p className="text-sm font-medium text-blue-800 dark:text-blue-300 mb-2">
                  مانده فلزات تا بالانس:
                </p>
                <div className="space-y-1.5">
                  {metalRemaining.map((item) => {
                    const percentage = item.line_grams > 0 
                      ? ((item.transacted_grams / item.line_grams) * 100)
                      : 0
                    return (
                      <div key={item.product_id} className="text-xs text-blue-700 dark:text-blue-400 flex items-center gap-2 flex-wrap">
                        <span className="font-medium">{item.product?.name || `محصول #${item.product_id}`}</span>
                        <span className="text-blue-500 dark:text-blue-400">•</span>
                        <span>مانده: <span className="font-medium">{item.remaining_grams.toLocaleString('fa-IR', { maximumFractionDigits: 3 })}</span> گرم</span>
                        {item.line_grams > 0 && (
                          <>
                            <span className="text-blue-500 dark:text-blue-400">•</span>
                            <span>کل: <span className="font-medium">{item.line_grams.toLocaleString('fa-IR', { maximumFractionDigits: 3 })}</span> گرم</span>
                            <span className="text-blue-500 dark:text-blue-400">•</span>
                            <span className="font-medium">{percentage.toLocaleString('fa-IR', { maximumFractionDigits: 1 })}%</span> ثبت شده
                          </>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <Label>محصول *</Label>
                  <select
                    value={productId}
                    onChange={(e) => handleProductChange(e.target.value)}
                    className="mt-2 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                    required
                  >
                    <option value="">انتخاب محصول</option>
                    {metalRemaining.map((item) => (
                      <option key={item.product_id} value={item.product_id}>
                        {item.product?.name || `محصول #${item.product_id}`} ({item.remaining_grams.toLocaleString('fa-IR', { maximumFractionDigits: 3 })} گرم باقی‌مانده)
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <Label>گرم *</Label>
                  <input
                    type="number"
                    step="0.001"
                    min="0.001"
                    value={grams}
                    onChange={(e) => setGrams(e.target.value)}
                    className="mt-2 h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                    required
                    disabled={!productId}
                  />
                </div>

                <div className="md:col-span-2">
                  <Label>وضعیت</Label>
                  <select
                    value={status}
                    onChange={(e) => setStatus(e.target.value)}
                    className="mt-2 h-11 w-full max-w-xs rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  >
                    {statusOptions.map((opt) => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    با انتخاب «تحویل/دریافت داده شده» موجودی انبار به‌روز می‌شود.
                  </p>
                </div>

                <div className="md:col-span-2">
                  <Label>یادداشت</Label>
                  <textarea
                    className="mt-2 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    rows={2}
                    placeholder="اختیاری"
                  />
                </div>
              </div>

              <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-800">
                <button
                  type="button"
                  onClick={handleClose}
                  className="inline-flex items-center gap-2 rounded-xl border border-gray-200 bg-white px-5 py-2.5 text-sm font-medium text-gray-700 transition hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                >
                  انصراف
                </button>
                <button
                  type="submit"
                  disabled={loading || metalRemaining.length === 0}
                  className="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {loading ? (
                    <>
                      <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      در حال ثبت...
                    </>
                  ) : (
                    'ثبت فلز'
                  )}
                </button>
              </div>
            </form>
          </>
        )}
      </div>
    </Modal>
  )
}
