'use client'
import { useState, useRef, useCallback } from 'react'

interface ScanResult {
  identified: boolean
  plant: string
  growthStage: string
  condition: string
  disease: string | null
  confidence: number
  severity: 'mild' | 'moderate' | 'critical' | 'none'
  actWithinHours: number | null
  summary: string
  cause: string
  organicTreatment: string[] | null
  chemicalTreatment: string[] | null
  prevention: string[]
  isCommonInKenya: boolean
}

const severityConfig = {
  none: { label: 'Healthy', bg: 'bg-leaf-50', text: 'text-leaf-700', border: 'border-leaf-200', icon: '✓' },
  mild: { label: 'Mild Issue', bg: 'bg-yellow-50', text: 'text-yellow-700', border: 'border-yellow-200', icon: '!' },
  moderate: { label: 'Moderate', bg: 'bg-orange-50', text: 'text-orange-700', border: 'border-orange-200', icon: '!!' },
  critical: { label: 'Critical', bg: 'bg-red-50', text: 'text-red-700', border: 'border-red-200', icon: '⚠' },
}

export default function Scanner() {
  const [image, setImage] = useState<string | null>(null)
  const [imageMime, setImageMime] = useState<string>('image/jpeg')
  const [scanning, setScanning] = useState(false)
  const [result, setResult] = useState<ScanResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'organic' | 'chemical'>('organic')
  const fileInputRef = useRef<HTMLInputElement>(null)
  const cameraInputRef = useRef<HTMLInputElement>(null)

  const processImage = useCallback(async (file: File) => {
    if (file.size > 10 * 1024 * 1024) {
      setError('Image too large. Please use a smaller photo.')
      return
    }

    const reader = new FileReader()
    reader.onload = async (e) => {
      const dataUrl = e.target?.result as string
      const base64 = dataUrl.split(',')[1]
      const mime = file.type || 'image/jpeg'

      setImage(dataUrl)
      setImageMime(mime)
      setResult(null)
      setError(null)
      setScanning(true)

      try {
        const res = await fetch('/api/scan', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ imageBase64: base64, mimeType: mime }),
        })
        const data = await res.json()
        if (data.error) throw new Error(data.error)
        setResult(data)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Scan failed. Please try again.')
      } finally {
        setScanning(false)
      }
    }
    reader.readAsDataURL(file)
  }, [])

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) processImage(file)
  }

  const resetScan = () => {
    setImage(null)
    setResult(null)
    setError(null)
    if (fileInputRef.current) fileInputRef.current.value = ''
    if (cameraInputRef.current) cameraInputRef.current.value = ''
  }

  return (
    <div className="px-4 py-5">
      {/* Hero text */}
      {!image && (
        <div className="animate-fade-up mb-6">
          <h2 className="font-display text-2xl font-bold text-soil-900 mb-1">
            Scan Your Crop
          </h2>
          <p className="text-soil-500 text-sm">
            Take a photo of any leaf, stem, or fruit. AI identifies diseases, pests & health issues instantly.
          </p>
        </div>
      )}

      {/* Image Preview / Upload Area */}
      {!image ? (
        <div className="animate-fade-up stagger-1 space-y-3">
          {/* Camera button - primary */}
          <button
            onClick={() => cameraInputRef.current?.click()}
            className="w-full h-52 rounded-2xl border-2 border-dashed border-leaf-300 bg-leaf-50 flex flex-col items-center justify-center gap-3 transition-all active:scale-95 active:bg-leaf-100"
          >
            <div className="w-16 h-16 rounded-2xl bg-leaf-600 flex items-center justify-center shadow-lg">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                <path d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                <circle cx="12" cy="13" r="4" stroke="white" strokeWidth="2"/>
              </svg>
            </div>
            <div className="text-center">
              <p className="font-display font-semibold text-leaf-700 text-lg">Take a Photo</p>
              <p className="text-leaf-500 text-xs mt-0.5">Use your camera for best results</p>
            </div>
          </button>

          {/* Upload from gallery */}
          <button
            onClick={() => fileInputRef.current?.click()}
            className="w-full py-4 rounded-2xl border border-soil-200 bg-white flex items-center justify-center gap-3 transition-all active:scale-95 active:bg-soil-50"
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
              <rect x="3" y="3" width="18" height="18" rx="3" stroke="#9ca3af" strokeWidth="2"/>
              <circle cx="8.5" cy="8.5" r="1.5" fill="#9ca3af"/>
              <path d="M21 15l-5-5L5 21" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            <span className="text-soil-600 font-medium text-sm">Upload from Gallery</span>
          </button>

          {/* Tips */}
          <div className="shamba-card p-4 mt-4">
            <p className="text-xs font-semibold text-soil-700 mb-2 font-display uppercase tracking-wide">📸 Better Scan Tips</p>
            <ul className="space-y-1.5">
              {[
                'Focus on the affected area (leaf, stem, fruit)',
                'Good lighting — avoid dark shadows',
                'Hold steady, close to the plant',
                'One plant part per scan works best',
              ].map((tip, i) => (
                <li key={i} className="flex items-start gap-2 text-xs text-soil-500">
                  <span className="text-leaf-500 mt-0.5 shrink-0">›</span>
                  {tip}
                </li>
              ))}
            </ul>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          {/* Image with scan overlay */}
          <div className="relative rounded-2xl overflow-hidden bg-black">
            <img src={image} alt="Scanned crop" className="w-full h-64 object-cover" />
            {scanning && (
              <div className="absolute inset-0 bg-black/40 flex flex-col items-center justify-center">
                <div className="scan-overlay scan-corners relative w-48 h-48">
                  <div className="absolute inset-0 border-2 border-leaf-400/30 rounded-lg"/>
                </div>
                <div className="mt-4 flex items-center gap-2">
                  <div className="spinner"/>
                  <span className="text-white text-sm font-medium">Analysing...</span>
                </div>
              </div>
            )}
            <button
              onClick={resetScan}
              className="absolute top-3 right-3 w-8 h-8 rounded-full bg-black/50 flex items-center justify-center text-white"
            >
              ✕
            </button>
          </div>

          {/* Error */}
          {error && (
            <div className="shamba-card p-4 bg-red-50 border-red-200">
              <p className="text-red-700 text-sm">{error}</p>
              <button onClick={resetScan} className="text-red-600 text-xs font-semibold mt-2 underline">
                Try again
              </button>
            </div>
          )}

          {/* Results */}
          {result && !scanning && (
            <div className="space-y-3 animate-fade-up">
              {/* Main result card */}
              <div className="shamba-card p-4">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h3 className="font-display font-bold text-xl text-soil-900">{result.plant}</h3>
                    <p className="text-xs text-soil-400 capitalize">{result.growthStage} stage</p>
                  </div>
                  <div className={`px-3 py-1.5 rounded-full text-xs font-bold border ${severityConfig[result.severity].bg} ${severityConfig[result.severity].text} ${severityConfig[result.severity].border}`}>
                    {severityConfig[result.severity].icon} {severityConfig[result.severity].label}
                  </div>
                </div>

                {result.disease && (
                  <div className="bg-soil-50 rounded-xl p-3 mb-3">
                    <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-1">Detected</p>
                    <p className="font-display font-semibold text-soil-800">{result.disease}</p>
                  </div>
                )}

                <p className="text-sm text-soil-600 leading-relaxed">{result.summary}</p>

                {/* Confidence + urgency */}
                <div className="flex items-center gap-3 mt-3">
                  <div className="flex-1">
                    <div className="flex justify-between text-xs text-soil-400 mb-1">
                      <span>Confidence</span>
                      <span className="font-semibold">{result.confidence}%</span>
                    </div>
                    <div className="h-1.5 bg-soil-100 rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full transition-all ${result.confidence >= 70 ? 'bg-leaf-500' : result.confidence >= 40 ? 'bg-amber-400' : 'bg-red-400'}`}
                        style={{ width: `${result.confidence}%` }}
                      />
                    </div>
                  </div>
                  {result.actWithinHours && (
                    <div className="bg-red-50 border border-red-200 rounded-lg px-2 py-1 text-center">
                      <p className="text-[10px] text-red-500 font-semibold uppercase">Act within</p>
                      <p className="text-red-700 font-display font-bold text-sm">{result.actWithinHours}h</p>
                    </div>
                  )}
                </div>
              </div>

              {/* Cause */}
              {result.cause && (
                <div className="shamba-card p-4 animate-fade-up stagger-1">
                  <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-2">📋 Probable Cause</p>
                  <p className="text-sm text-soil-600">{result.cause}</p>
                </div>
              )}

              {/* Treatment tabs */}
              {(result.organicTreatment || result.chemicalTreatment) && result.severity !== 'none' && (
                <div className="shamba-card overflow-hidden animate-fade-up stagger-2">
                  <div className="flex border-b border-gray-100">
                    {result.organicTreatment && (
                      <button
                        onClick={() => setActiveTab('organic')}
                        className={`flex-1 py-3 text-xs font-semibold transition-colors ${activeTab === 'organic' ? 'text-leaf-600 border-b-2 border-leaf-500' : 'text-soil-400'}`}
                      >
                        🌿 Organic
                      </button>
                    )}
                    {result.chemicalTreatment && (
                      <button
                        onClick={() => setActiveTab('chemical')}
                        className={`flex-1 py-3 text-xs font-semibold transition-colors ${activeTab === 'chemical' ? 'text-soil-700 border-b-2 border-soil-400' : 'text-soil-400'}`}
                      >
                        🧪 Chemical
                      </button>
                    )}
                  </div>
                  <div className="p-4">
                    <p className="text-[10px] font-semibold text-soil-400 uppercase tracking-wide mb-2">Treatment Steps</p>
                    {activeTab === 'organic' && result.organicTreatment && (
                      <ol className="space-y-2">
                        {result.organicTreatment.map((step, i) => (
                          <li key={i} className="flex items-start gap-3 text-sm text-soil-600">
                            <span className="w-5 h-5 rounded-full bg-leaf-100 text-leaf-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">{i + 1}</span>
                            {step}
                          </li>
                        ))}
                      </ol>
                    )}
                    {activeTab === 'chemical' && result.chemicalTreatment && (
                      <div>
                        <ol className="space-y-2">
                          {result.chemicalTreatment.map((step, i) => (
                            <li key={i} className="flex items-start gap-3 text-sm text-soil-600">
                              <span className="w-5 h-5 rounded-full bg-amber-100 text-amber-700 text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">{i + 1}</span>
                              {step}
                            </li>
                          ))}
                        </ol>
                        <p className="text-xs text-amber-600 mt-3 bg-amber-50 rounded-lg p-2">
                          ⚠️ Visit your nearest agrovet to confirm products and dosage
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Prevention */}
              {result.prevention && result.prevention.length > 0 && (
                <div className="shamba-card p-4 animate-fade-up stagger-3">
                  <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-2">🛡️ Prevention</p>
                  <ul className="space-y-1.5">
                    {result.prevention.map((tip, i) => (
                      <li key={i} className="flex items-start gap-2 text-sm text-soil-600">
                        <span className="text-leaf-500 mt-0.5 shrink-0">›</span>
                        {tip}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Kenya flag */}
              {result.isCommonInKenya && (
                <div className="text-center text-xs text-soil-400 pb-2">
                  🇰🇪 This issue is commonly reported in Kenya
                </div>
              )}

              {/* Scan again */}
              <button
                onClick={resetScan}
                className="w-full py-4 bg-leaf-600 text-white rounded-2xl font-display font-semibold text-base active:scale-95 transition-transform shadow-lg shadow-leaf-200"
              >
                Scan Another Crop
              </button>
            </div>
          )}
        </div>
      )}

      {/* Hidden file inputs */}
      <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleFileChange} />
      <input ref={cameraInputRef} type="file" accept="image/*" capture="environment" className="hidden" onChange={handleFileChange} />
    </div>
  )
}
