import bbox from '@turf/bbox'
import squareGrid from '@turf/square-grid'
import type { Feature, FeatureCollection, Polygon } from 'geojson'
import type { CropType, ZoneFeatureProperties } from './cropZoningTypes'

const CROPS: CropType[] = ['wheat', 'canola', 'saffron']

function ruleBasedCropAssignment(
  index: number,
  coords: number[][][]
): { crop: CropType; matchPercent: number; waterNeed: string; estimatedProfit: string; reason: string; criteria: { name: string; value: number }[] } {
  const lat = coords[0]?.[0]?.[1] ?? 35
  const lng = coords[0]?.[0]?.[0] ?? 51
  const seed = index * 7 + Math.floor(lat * 100) + Math.floor(lng * 100)
  const cropIndex = Math.abs(seed) % CROPS.length
  const crop = CROPS[cropIndex]
  const matchPercent = 60 + (Math.abs(seed) % 35)
  const waterNeeds: Record<CropType, string> = {
    wheat: '۴۵۰۰-۵۵۰۰ m³/ha',
    canola: '۵۰۰۰-۶۰۰۰ m³/ha',
    saffron: '۳۰۰۰-۴۰۰۰ m³/ha'
  }
  const profits: Record<CropType, string> = {
    wheat: '۱۵-۲۵ میلیون/هکتار',
    canola: '۲۰-۳۵ میلیون/هکتار',
    saffron: '۵۰-۱۵۰ میلیون/هکتار'
  }
  const reasons: Record<CropType, string> = {
    wheat: 'دمای مناسب، خاک حاصلخیز، دسترسی به آب کافی',
    canola: 'شرایط اقلیمی مساعد، نیاز آبی قابل تأمین',
    saffron: 'ارتفاع و آب و هوای خشک مناسب، پتانسیل سود بالا'
  }
  const criteria = [
    { name: 'دما', value: 70 + (Math.abs(seed) % 25) },
    { name: 'بارش', value: 60 + (Math.abs(seed + 3) % 30) },
    { name: 'خاک', value: 65 + (Math.abs(seed + 5) % 30) },
    { name: 'آب', value: 55 + (Math.abs(seed + 7) % 40) }
  ]
  return {
    crop,
    matchPercent,
    waterNeed: waterNeeds[crop],
    estimatedProfit: profits[crop],
    reason: reasons[crop],
    criteria
  }
}

export function createZonedGrid(
  polygonFeature: Feature<Polygon>,
  cellSideKm = 0.15
): FeatureCollection<Polygon, ZoneFeatureProperties> {
  const bboxArr = bbox(polygonFeature)
  const grid = squareGrid(bboxArr, cellSideKm, {
    units: 'kilometers',
    mask: polygonFeature
  })

  const features: Feature<Polygon, ZoneFeatureProperties>[] = grid.features.map((f, i) => {
    const coords = (f.geometry as Polygon).coordinates
    const assigned = ruleBasedCropAssignment(i, coords)
    return {
      ...f,
      properties: {
        zoneId: `zone-${i}`,
        crop: assigned.crop,
        matchPercent: assigned.matchPercent,
        waterNeed: assigned.waterNeed,
        estimatedProfit: assigned.estimatedProfit,
        reason: assigned.reason,
        criteria: assigned.criteria
      }
    }
  })

  return {
    type: 'FeatureCollection',
    features
  }
}

/**
 * Creates grid geometry only (no crop assignment) for sending to POST /api/crop-zoning/zones/initial/
 */
export function createGridFromPolygon(
  polygonFeature: Feature<Polygon>,
  cellSideKm = 0.15
): FeatureCollection<Polygon, { index?: number }> {
  const bboxArr = bbox(polygonFeature)
  const grid = squareGrid(bboxArr, cellSideKm, {
    units: 'kilometers',
    mask: polygonFeature
  })
  const features = grid.features.map((f, i) => ({
    ...f,
    properties: { index: i }
  }))
  return {
    type: 'FeatureCollection',
    features
  }
}
