'use client'
import { useState } from 'react'

const KENYA_COUNTIES = [
  'Baringo','Bomet','Bungoma','Busia','Elgeyo Marakwet','Embu','Garissa',
  'Homa Bay','Isiolo','Kajiado','Kakamega','Kericho','Kiambu','Kilifi',
  'Kirinyaga','Kisii','Kisumu','Kitui','Kwale','Laikipia','Lamu','Machakos',
  'Makueni','Mandera','Marsabit','Meru','Migori','Mombasa','Muranga','Nairobi',
  'Nakuru','Nandi','Narok','Nyandarua','Nyamira','Nyeri','Samburu','Siaya',
  'Taita Taveta','Tana River','Tharaka Nithi','Trans Nzoia','Turkana',
  'Uasin Gishu','Vihiga','Wajir','West Pokot'
]

interface CropRec {
  crop: string
  variety: string
  suitabilityScore: number
  plantingWindow: string
  expectedYield: string
  marketDemand: 'high' | 'medium' | 'low'
  profitability: 'high' | 'medium' | 'low'
  daysToHarvest: number
  waterRequirement: 'low' | 'medium' | 'high'
  diseaseRisk: 'low' | 'medium' | 'low'
  tip: string
}

interface PlantAdvice {
  season: string
  seasonNote: string
  recommendations: CropRec[]
  generalAdvice: string
  inputsNeeded: string[]
  warningFlags: string[]
}

const demandColors = {
  high: 'text-leaf-600 bg-leaf-50',
  medium: 'text-amber-600 bg-amber-50',
  low: 'text-gray-500 bg-gray-100',
}

const profitColors = {
  high: 'text-leaf-600',
  medium: 'text-amber-600',
  low: 'text-gray-500',
}

const profitIcons = { high: '₭₭₭', medium: '₭₭', low: '₭' }

export default function WhatToPlant() {
  const [county, setCounty] = useState('')
  const [landSize, setLandSize] = useState('')
  const [waterAccess, setWaterAccess] = useState('')
  const [budget, setBudget] = useState('')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<PlantAdvice | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [expanded, setExpanded] = useState<number | null>(0)

  const handleSubmit = async () => {
    if (!county || !landSize || !waterAccess || !budget) {
      setError('Please fill in all fields')
      return
    }
    setLoading(true)
    setError(null)
    setResult(null)

    try {
      const res = await fetch('/api/plant-advice', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ county, landSize, waterAccess, budget }),
      })
      const data = await res.json()
      if (data.error) throw new Error(data.error)
      setResult(data)
      setExpanded(0)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to get recommendations')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="px-4 py-5">
      <div className="animate-fade-up mb-5">
        <h2 className="font-display text-2xl font-bold text-soil-900 mb-1">What to Plant</h2>
        <p className="text-soil-500 text-sm">Get AI crop recommendations for your farm, right now.</p>
      </div>

      {!result ? (
        <div className="space-y-4 animate-fade-up stagger-1">
          {/* County */}
          <div>
            <label className="block text-xs font-semibold text-soil-600 uppercase tracking-wide mb-1.5">County</label>
            <select
              value={county}
              onChange={e => setCounty(e.target.value)}
              className="w-full px-4 py-3.5 rounded-xl border border-soil-200 bg-white text-soil-800 text-sm focus:outline-none focus:ring-2 focus:ring-leaf-400 appearance-none"
            >
              <option value="">Select your county</option>
              {KENYA_COUNTIES.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>

          {/* Land size */}
          <div>
            <label className="block text-xs font-semibold text-soil-600 uppercase tracking-wide mb-1.5">Land Size</label>
            <div className="grid grid-cols-3 gap-2">
              {['Under 1 acre', '1-5 acres', 'Over 5 acres'].map(size => (
                <button
                  key={size}
                  onClick={() => setLandSize(size)}
                  className={`py-3 rounded-xl border text-sm font-medium transition-all ${landSize === size ? 'bg-leaf-600 text-white border-leaf-600' : 'bg-white border-soil-200 text-soil-600'}`}
                >
                  {size}
                </button>
              ))}
            </div>
          </div>

          {/* Water access */}
          <div>
            <label className="block text-xs font-semibold text-soil-600 uppercase tracking-wide mb-1.5">Water Access</label>
            <div className="grid grid-cols-3 gap-2">
              {[
                { val: 'rain-only', label: 'Rain only' },
                { val: 'borehole', label: 'Borehole' },
                { val: 'irrigation', label: 'Irrigation' },
              ].map(opt => (
                <button
                  key={opt.val}
                  onClick={() => setWaterAccess(opt.val)}
                  className={`py-3 rounded-xl border text-sm font-medium transition-all ${waterAccess === opt.val ? 'bg-leaf-600 text-white border-leaf-600' : 'bg-white border-soil-200 text-soil-600'}`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Budget */}
          <div>
            <label className="block text-xs font-semibold text-soil-600 uppercase tracking-wide mb-1.5">Input Budget</label>
            <div className="grid grid-cols-3 gap-2">
              {[
                { val: 'low', label: 'Low\n< 5K' },
                { val: 'medium', label: 'Medium\n5-20K' },
                { val: 'high', label: 'High\n> 20K' },
              ].map(opt => (
                <button
                  key={opt.val}
                  onClick={() => setBudget(opt.val)}
                  className={`py-3 rounded-xl border text-sm font-medium transition-all whitespace-pre-line leading-tight ${budget === opt.val ? 'bg-soil-700 text-white border-soil-700' : 'bg-white border-soil-200 text-soil-600'}`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {error && <p className="text-red-600 text-sm bg-red-50 px-3 py-2 rounded-lg">{error}</p>}

          <button
            onClick={handleSubmit}
            disabled={loading}
            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 flex items-center justify-center gap-2 disabled:opacity-60"
          >
            {loading ? (
              <><div className="spinner !border-white/30 !border-t-white"/>Analysing your farm...</>
            ) : (
              '🌱 Get Crop Recommendations'
            )}
          </button>
        </div>
      ) : (
        <div className="space-y-4 animate-fade-up">
          {/* Season badge */}
          <div className="shamba-card p-4 bg-gradient-to-r from-leaf-50 to-sky-farm border-leaf-200">
            <div className="flex items-center gap-2 mb-1">
              <span className="text-lg">🌦️</span>
              <span className="font-display font-semibold text-leaf-800 capitalize">{result.season}</span>
            </div>
            <p className="text-sm text-soil-600">{result.seasonNote}</p>
          </div>

          {/* Warning flags */}
          {result.warningFlags && result.warningFlags.length > 0 && (
            <div className="shamba-card p-4 bg-amber-50 border-amber-200">
              <p className="text-xs font-semibold text-amber-600 uppercase tracking-wide mb-2">⚠️ Watch Out</p>
              {result.warningFlags.map((flag, i) => (
                <p key={i} className="text-sm text-amber-700">• {flag}</p>
              ))}
            </div>
          )}

          {/* Crop cards */}
          <div>
            <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-3">
              Top Crops for {county}
            </p>
            <div className="space-y-2">
              {result.recommendations.map((crop, i) => (
                <div key={i} className="shamba-card overflow-hidden">
                  <button
                    onClick={() => setExpanded(expanded === i ? null : i)}
                    className="w-full p-4 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl bg-leaf-50 flex items-center justify-center">
                        <span className="text-xl">
                          {['🌽','🍅','🥬','🧅','🥔','🫘','🌿','🍠'][i % 8]}
                        </span>
                      </div>
                      <div className="text-left">
                        <p className="font-display font-semibold text-soil-800">{crop.crop}</p>
                        <p className="text-xs text-soil-400">{crop.variety}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="text-right">
                        <div className={`text-xs font-semibold px-2 py-0.5 rounded-full ${demandColors[crop.marketDemand]}`}>
                          {crop.marketDemand} demand
                        </div>
                        <div className={`text-xs font-semibold ${profitColors[crop.profitability]} text-right mt-0.5`}>
                          {profitIcons[crop.profitability]}
                        </div>
                      </div>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className={`text-soil-300 transition-transform ${expanded === i ? 'rotate-180' : ''}`}>
                        <path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                      </svg>
                    </div>
                  </button>

                  {expanded === i && (
                    <div className="px-4 pb-4 space-y-3 border-t border-gray-50">
                      {/* Suitability bar */}
                      <div className="pt-3">
                        <div className="flex justify-between text-xs text-soil-400 mb-1">
                          <span>Suitability for {county}</span>
                          <span className="font-semibold text-leaf-600">{crop.suitabilityScore}%</span>
                        </div>
                        <div className="h-2 bg-soil-100 rounded-full overflow-hidden">
                          <div className="h-full bg-leaf-500 rounded-full" style={{ width: `${crop.suitabilityScore}%` }}/>
                        </div>
                      </div>

                      {/* Stats grid */}
                      <div className="grid grid-cols-2 gap-2">
                        {[
                          { label: 'Plant when', val: crop.plantingWindow },
                          { label: 'Harvest in', val: `${crop.daysToHarvest} days` },
                          { label: 'Expected yield', val: crop.expectedYield },
                          { label: 'Water needs', val: crop.waterRequirement },
                        ].map((stat) => (
                          <div key={stat.label} className="bg-soil-50 rounded-xl p-2.5">
                            <p className="text-[10px] text-soil-400 uppercase font-semibold">{stat.label}</p>
                            <p className="text-sm font-semibold text-soil-700 mt-0.5 capitalize">{stat.val}</p>
                          </div>
                        ))}
                      </div>

                      {/* Tip */}
                      <div className="bg-leaf-50 rounded-xl p-3 flex gap-2">
                        <span className="text-base">💡</span>
                        <p className="text-sm text-leaf-800">{crop.tip}</p>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* General advice */}
          <div className="shamba-card p-4">
            <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-2">Seasonal Advice</p>
            <p className="text-sm text-soil-600">{result.generalAdvice}</p>
          </div>

          {/* Inputs needed */}
          {result.inputsNeeded && result.inputsNeeded.length > 0 && (
            <div className="shamba-card p-4">
              <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-2">🛒 Inputs to Source</p>
              <div className="flex flex-wrap gap-2">
                {result.inputsNeeded.map((input, i) => (
                  <span key={i} className="text-xs bg-soil-100 text-soil-600 px-3 py-1.5 rounded-full">{input}</span>
                ))}
              </div>
            </div>
          )}

          {/* Reset */}
          <button
            onClick={() => { setResult(null); setError(null) }}
            className="w-full py-3.5 border-2 border-leaf-300 text-leaf-700 rounded-2xl font-semibold text-sm active:scale-95 transition-transform"
          >
            Check Different Farm
          </button>
        </div>
      )}
    </div>
  )
}
