"use client";
import { useForm, type Resolver } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { extendedFactors, compareScenarios, type Scenario, type Tillage } from "@/lib/calc";
import { BarChart } from "@/components/BarChart";
import { useEffect, useState } from "react";
import { load, save } from "@/lib/storage";
// import { useReactToPrint } from "react-to-print";
import ProtectedRoute from "@/components/ProtectedRoute";
import { useAuth } from "@/contexts/AuthContext";
import { apiClient } from "@/lib/api";

const schema = z.object({
  // 1. Date de bază despre organizație/firma
  name: z.string().min(2), // Denumire
  location: z.string().default("România"), // Locație
  activityDomain: z.string().default("Agricultură"), // Domeniu de activitate
  cultivatedAreaHa: z.coerce.number().min(0), // Suprafață agricolă cultivată
  cropTypes: z.string().default("Grâu, porumb, floarea-soarelui"), // Tipuri de culturi
  animalCount: z.coerce.number().min(0).optional(), // Număr de animale
  infrastructure: z.string().default("Ferme, silozuri, utilaje agricole"), // Infrastructură
  
  // 2. Consum de energie (electricitate, combustibili)
  electricityKWh: z.coerce.number().min(0), // Facturi la curent electric
  renewableSharePct: z.coerce.number().min(0).max(100).default(0), // Surse de energie regenerabilă
  dieselL: z.coerce.number().min(0), // Consum motorină
  gasolineL: z.coerce.number().min(0).default(0), // Consum benzină
  
  // 3. Utilizarea inputurilor agricole
  fertilizerN_Kg: z.coerce.number().min(0), // Cantitate Azot (N)
  fertilizerN_Type: z.string().optional(), // Tip îngrășământ Azot
  fertilizerP2O5_Kg: z.coerce.number().min(0).optional(), // Cantitate Fosfor (P2O5)
  fertilizerP_Type: z.string().optional(), // Tip îngrășământ Fosfor
  fertilizerK2O_Kg: z.coerce.number().min(0).optional(), // Cantitate Potasiu (K2O)
  fertilizerK_Type: z.string().optional(), // Tip îngrășământ Potasiu
  pesticideType: z.string().optional(), // Tip pesticid
  pesticideDosePerHa: z.coerce.number().min(0).optional(), // Doză per hectar
  pesticideApplicationsPerSeason: z.coerce.number().min(0).optional(), // Frecvență
  seedType: z.string().optional(), // Tip semințe/material săditor
  importSharePct: z.coerce.number().min(0).max(100).optional(), // Proporția inputurilor importate
  
  // 4. Managementul terenului și solului
  soilType: z.string().optional(), // Tipul de sol
  previousUse: z.string().optional(), // Utilizare precedentă
  irrigationM3: z.coerce.number().min(0).optional(), // Irigare
  drainage: z.boolean().optional(), // Drenaj
  tillage: z.enum(["plough","min_till","no_till"]).default("plough"), // Arături / lucrare minimă a solului
  agroforestry: z.boolean().optional(), // Agroforestry
  coverCropsHa: z.coerce.number().min(0).default(0), // Acoperire vegetală / culturi intermediare
  erosionDegradationNotes: z.string().optional(), // Eroziune, degradare
  soilFertilityNotes: z.string().optional(), // Fertilitatea solului
  
  // 5. Transporte și lanț de aprovizionare
  internalTransportDistances: z.coerce.number().min(0).default(0), // Transporturi interne: distanțe
  internalTransportVehicleType: z.string().default("Tractor"), // tip de vehicule
  internalTransportFrequency: z.string().default("Zilnic"), // frecvență
  inputTransportFuel: z.string().default("Transport combustibili"), // Transporturile de inputuri - combustibili
  inputTransportSeeds: z.string().default("Transport semințe"), // Transporturile de inputuri - semințe
  inputTransportChemicals: z.string().default("Transport inputuri chimice"), // Transporturile de inputuri - chimice
  exportCollectionProduction: z.string().default("Export/colectare producție"), // Exporturile/colectările producției
  storageProcessingStorage: z.string().default("Depozitare"), // Depozitare
  storageProcessingProcessing: z.string().default("Procesare"), // Procesare
  storageProcessingPackaging: z.string().default("Ambalare"), // Ambalare
  storageProcessingEquipment: z.string().default("Utilaje"), // Utilaje
  storageProcessingEnergyConsumed: z.coerce.number().min(0).default(1000), // Energie consumată
  
  // 6. Emisii directe și indirecte
  onSiteEngines: z.string().default("Motoare utilaje agricole"), // Emisii directe la fața locului
  onSiteGenerators: z.string().default("Generatoare"), // Generatoare
  onSiteEquipment: z.string().default("Echipamente"), // Echipamente
  importedElectricity: z.string().default("Electricitate importată"), // Emisii indirecte prin electricitate importată
  heating: z.string().default("Încălzire"), // Încălzire
  fertilizerEmissions: z.string().default("Emisii din fertilizanți"), // Emisii din fertilizanți
  pesticideEmissions: z.string().default("Emisii din pesticide"), // Emisii din pesticide
  lcaModels: z.string().default("Modele LCA"), // Modele LCA și emisie globale
  
  // 7. Factori de emisie (emission factors)
  emissionFactorsLocalized: z.string().default("Factori românești/UE"), // Factori localizați
  emissionFactorsGeneric: z.string().default("IPCC, baze de date EU"), // Factori generici recunoscuți
  fuelEmissionFactors: z.string().default("Factori combustibili"), // Factori pentru combustibili
  energyEmissionFactors: z.string().default("Factori energie"), // Factori pentru energie
  inputEmissionFactors: z.string().default("Factori inputuri"), // Factori pentru inputuri
  pricePerTonneEUR: z.coerce.number().min(0).default(30), // Preț per tonă CO2
  
  // 8. Date despre producție / output
  productionTonnage: z.coerce.number().min(0).default(1000), // Cantități produse (tonaje)
  productionVolume: z.coerce.number().min(0).default(500), // volume
  productionCalendar: z.string().default("Anual"), // Calendarul producției
  productionSeasons: z.string().default("Primăvară, toamnă"), // sezoane
  productionTypeGreen: z.string().default("Verdele"), // Tipul de producție - verdele
  productionTypeProcessing: z.string().default("Procesare"), // Tipul de producție - procesare
  productionTypeRawMaterial: z.string().default("Materie primă"), // Tipul de producție - materie primă
  finishingPackaging: z.string().default("Finisare/ambalaj"), // Finisare/ambalaj
  distribution: z.string().default("Distribuție"), // Distribuție
  
  // 9. Date financiare relevante
  energyCosts: z.coerce.number().min(0).default(10000), // Costuri legate de energie
  fuelCosts: z.coerce.number().min(0).default(15000), // combustibili
  fertilizerCosts: z.coerce.number().min(0).default(8000), // fertilizanți
  sellingPrices: z.coerce.number().min(0).default(200), // Prețuri de vânzare
  margins: z.coerce.number().min(0).default(50), // marje
  transitionCostsTechnology: z.coerce.number().min(0).default(5000), // Costuri tranziție - tehnologii
  transitionCostsGreenEquipment: z.coerce.number().min(0).default(10000), // Costuri tranziție - echipamente verzi
  transitionCostsModernization: z.coerce.number().min(0).default(15000), // Costuri tranziție - modernizare
  
  // 10. Alte date auxiliare
  irrigationCalendar: z.string().default("Iunie-August"), // Calendar/regimul de irigare
  localClimate: z.string().default("Temperat continental"), // climă locală
  temperatureData: z.string().default("Temperaturi medii"), // Temperaturi
  precipitationData: z.string().default("Precipitații medii"), // Precipitații
  agriculturalWasteManagement: z.string().default("Management deșeuri agricole"), // Managementul deșeurilor agricole
  residueManagement: z.string().default("Management reziduuri"), // Managementul reziduurilor
  workingHours: z.coerce.number().min(0).default(2000), // ore de muncă
  personalTransport: z.string().default("Transport personal"), // Transport personal
  
  // Scenariu proiect
  project_reductionN_pct: z.coerce.number().min(0).max(100).default(20),
  project_greenEnergy_pct: z.coerce.number().min(0).max(100).default(10),
  project_tillage: z.enum(["plough","min_till","no_till"]).default("no_till"),
  project_coverCropsHa: z.coerce.number().min(0).default(50),
});

type FormValues = z.infer<typeof schema>;

const SLIDES = [
  { id: 0, title: "Informații de bază", description: "Date generale despre organizația dumneavoastră" },
  { id: 1, title: "Energie", description: "Consumul de energie și combustibili" },
  { id: 2, title: "Inputuri agricole", description: "Îngrășăminte, pesticide și semințe" },
  { id: 3, title: "Management teren", description: "Sol, irigare și lucrări agricole" },
  { id: 4, title: "Transport și aprovizionare", description: "Transporturi și lanțul de aprovizionare" },
  { id: 5, title: "Emisii", description: "Emisii directe și indirecte" },
  { id: 6, title: "Factori de emisie", description: "Parametrii pentru calculele de emisii" },
  { id: 7, title: "Producție", description: "Date despre producția și outputul" },
  { id: 8, title: "Date financiare", description: "Costuri, prețuri și investiții" },
  { id: 9, title: "Date auxiliare", description: "Climă, deșeuri și personal" },
  { id: 10, title: "Scenariu proiect", description: "Modificări pentru scenariul proiectului" },
];

export default function WizardPage() {
  const [currentSlide, setCurrentSlide] = useState(0);
  const { register, handleSubmit, watch } = useForm<FormValues>({
    resolver: zodResolver(schema) as Resolver<FormValues>,
    defaultValues: load<FormValues>("agricarbon-demo-form", {
      // 1. Date de bază despre organizație/firma
      name: "Fermă demo",
      location: "România",
      activityDomain: "Agricultură",
      cultivatedAreaHa: 100,
      cropTypes: "Grâu, porumb, floarea-soarelui",
      animalCount: 0,
      infrastructure: "Ferme, silozuri, utilaje agricole",
      
      // 2. Consum de energie
      electricityKWh: 50000,
      renewableSharePct: 0,
      dieselL: 12000,
      gasolineL: 0,
      
      // 3. Utilizarea inputurilor agricole
      fertilizerN_Kg: 15000,
      fertilizerN_Type: "Uree",
      fertilizerP2O5_Kg: 5000,
      fertilizerP_Type: "MAP",
      fertilizerK2O_Kg: 3000,
      fertilizerK_Type: "KCl",
      pesticideType: "Erbicid",
      pesticideDosePerHa: 2,
      pesticideApplicationsPerSeason: 2,
      seedType: "Grâu",
      importSharePct: 20,
      
      // 4. Managementul terenului și solului
      soilType: "Cernoziom",
      previousUse: "Monocultură",
      irrigationM3: 10000,
      drainage: false,
      tillage: "plough",
      agroforestry: false,
      coverCropsHa: 0,
      erosionDegradationNotes: "Eroziune ușoară",
      soilFertilityNotes: "Analize recente: pH 6.5",
      
      // 5. Transporte și lanț de aprovizionare
      internalTransportDistances: 50,
      internalTransportVehicleType: "Tractor",
      internalTransportFrequency: "Zilnic",
      inputTransportFuel: "Transport combustibili",
      inputTransportSeeds: "Transport semințe",
      inputTransportChemicals: "Transport inputuri chimice",
      exportCollectionProduction: "Export/colectare producție",
      storageProcessingStorage: "Depozitare",
      storageProcessingProcessing: "Procesare",
      storageProcessingPackaging: "Ambalare",
      storageProcessingEquipment: "Utilaje",
      storageProcessingEnergyConsumed: 1000,
      
      // 6. Emisii directe și indirecte
      onSiteEngines: "Motoare utilaje agricole",
      onSiteGenerators: "Generatoare",
      onSiteEquipment: "Echipamente",
      importedElectricity: "Electricitate importată",
      heating: "Încălzire",
      fertilizerEmissions: "Emisii din fertilizanți",
      pesticideEmissions: "Emisii din pesticide",
      lcaModels: "Modele LCA",
      
      // 7. Factori de emisie
      emissionFactorsLocalized: "Factori românești/UE",
      emissionFactorsGeneric: "IPCC, baze de date EU",
      fuelEmissionFactors: "Factori combustibili",
      energyEmissionFactors: "Factori energie",
      inputEmissionFactors: "Factori inputuri",
      pricePerTonneEUR: 30,
      
      // 8. Date despre producție / output
      productionTonnage: 1000,
      productionVolume: 500,
      productionCalendar: "Anual",
      productionSeasons: "Primăvară, toamnă",
      productionTypeGreen: "Verdele",
      productionTypeProcessing: "Procesare",
      productionTypeRawMaterial: "Materie primă",
      finishingPackaging: "Finisare/ambalaj",
      distribution: "Distribuție",
      
      // 9. Date financiare relevante
      energyCosts: 10000,
      fuelCosts: 15000,
      fertilizerCosts: 8000,
      sellingPrices: 200,
      margins: 50,
      transitionCostsTechnology: 5000,
      transitionCostsGreenEquipment: 10000,
      transitionCostsModernization: 15000,
      
      // 10. Alte date auxiliare
      irrigationCalendar: "Iunie-August",
      localClimate: "Temperat continental",
      temperatureData: "Temperaturi medii",
      precipitationData: "Precipitații medii",
      agriculturalWasteManagement: "Management deșeuri agricole",
      residueManagement: "Management reziduuri",
      workingHours: 2000,
      personalTransport: "Transport personal",
      
      // Scenariu proiect
      project_reductionN_pct: 20,
      project_greenEnergy_pct: 10,
      project_tillage: "no_till",
      project_coverCropsHa: 50,
    }),
  });

  // Persist form values
  const values = watch();
  useEffect(() => {
    save("agricarbon-demo-form", values);
  }, [values]);

  const [result, setResult] = useState<null | ReturnType<typeof compareScenarios>>(null);
  const [factors] = useState(extendedFactors);
  const [saving, setSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState<string | null>(null);
  const [savedReportId, setSavedReportId] = useState<string | null>(null);
  const { user } = useAuth();

  const nextSlide = () => {
    if (currentSlide < SLIDES.length - 1) {
      setCurrentSlide(currentSlide + 1);
    }
  };

  const prevSlide = () => {
    if (currentSlide > 0) {
      setCurrentSlide(currentSlide - 1);
    }
  };

  const goToSlide = (slideIndex: number) => {
    setCurrentSlide(slideIndex);
  };

  // Componente pentru fiecare slide
  const renderSlide = (slideIndex: number) => {
    switch (slideIndex) {
      case 0:
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Denumire</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("name")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Locația</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("location")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Domeniu de activitate</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("activityDomain")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Suprafață cultivată (ha)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("cultivatedAreaHa")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Tipuri de culturi</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("cropTypes")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Număr de animale (opțional)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("animalCount")} />
            </div>
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Infrastructură</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("infrastructure")} />
            </div>
          </div>
        );
      case 1:
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Electricitate (kWh/an)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("electricityKWh")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Energie verde (%)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("renewableSharePct")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Motorină (L/an)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("dieselL")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Benzină (L/an)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("gasolineL")} />
            </div>
          </div>
        );
      case 2:
        return (
          <div className="space-y-8">
            {/* Îngrășăminte */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Îngrășăminte</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Îngrășăminte N (kg/an)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerN_Kg")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tip îngrășământ N</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerN_Type")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Fosfați P2O5 (kg/an)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerP2O5_Kg")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tip fosfați</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerP_Type")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Potasiu K2O (kg/an)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerK2O_Kg")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tip potasiu</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerK_Type")} />
                </div>
              </div>
            </div>

            {/* Pesticide */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Pesticide</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tip pesticide</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("pesticideType")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Doză/ha (kg sau L)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("pesticideDosePerHa")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Frecvență (aplicări/sezon)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("pesticideApplicationsPerSeason")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Proporție inputuri importate (%)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("importSharePct")} />
                </div>
              </div>
            </div>

            {/* Semințe */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Semințe și material săditor</h4>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Tip semințe/material săditor</label>
                <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("seedType")} />
              </div>
            </div>
          </div>
        );
      case 3:
        return (
          <div className="space-y-8">
            {/* Caracteristici sol */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Caracteristici sol</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tipul de sol</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("soilType")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Utilizare precedentă</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("previousUse")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Irigare (m³/an)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("irrigationM3")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Lucrare sol</label>
                  <select className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("tillage")}>
                    <option value="plough">Arat</option>
                    <option value="min_till">Min-till</option>
                    <option value="no_till">No-till</option>
                  </select>
                </div>
              </div>
            </div>

            {/* Opțiuni și note */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Opțiuni și note</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="flex items-center">
                    <input type="checkbox" className="w-4 h-4 text-emerald-600 border-gray-300 rounded focus:ring-emerald-500" {...register("drainage")} />
                    <label className="ml-2 text-sm font-medium text-gray-700">Drenaj</label>
                  </div>
                  <div className="flex items-center">
                    <input type="checkbox" className="w-4 h-4 text-emerald-600 border-gray-300 rounded focus:ring-emerald-500" {...register("agroforestry")} />
                    <label className="ml-2 text-sm font-medium text-gray-700">Agroforestry</label>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Acoperire vegetală / culturi intermediare (ha)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("coverCropsHa")} />
                </div>
              </div>
            </div>

            {/* Note și observații */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Note și observații</h4>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Eroziune / degradare (note)</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("erosionDegradationNotes")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Fertilitatea solului (analize/observații)</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("soilFertilityNotes")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 4:
        return (
          <div className="space-y-8">
            {/* Transporturi interne */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Transporturi interne</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Distanțe (km)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("internalTransportDistances")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tip de vehicule</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("internalTransportVehicleType")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Frecvență</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("internalTransportFrequency")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Export/colectare producție</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("exportCollectionProduction")} />
                </div>
              </div>
            </div>

            {/* Transport inputuri */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Transport inputuri</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Transport combustibili</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("inputTransportFuel")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Transport semințe</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("inputTransportSeeds")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Transport inputuri chimice</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("inputTransportChemicals")} />
                </div>
              </div>
            </div>

            {/* Depozitare și procesare */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Depozitare și procesare</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Depozitare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("storageProcessingStorage")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Procesare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("storageProcessingProcessing")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Ambalare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("storageProcessingPackaging")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Utilaje</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("storageProcessingEquipment")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Energie consumată (kWh)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("storageProcessingEnergyConsumed")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 5:
        return (
          <div className="space-y-8">
            {/* Emisii directe */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Emisii directe</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Motoare utilaje</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("onSiteEngines")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Generatoare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("onSiteGenerators")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Echipamente</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("onSiteEquipment")} />
                </div>
              </div>
            </div>

            {/* Emisii indirecte */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Emisii indirecte</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Electricitate importată</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("importedElectricity")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Încălzire</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("heating")} />
                </div>
              </div>
            </div>

            {/* Emisii din inputuri */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Emisii din inputuri</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Emisii din fertilizanți</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerEmissions")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Emisii din pesticide</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("pesticideEmissions")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Modele LCA și emisie globală</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("lcaModels")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 6:
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Factori localizați (românești/UE)</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("emissionFactorsLocalized")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Factori generici recunoscuți (IPCC, EU)</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("emissionFactorsGeneric")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Factori pentru combustibili</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fuelEmissionFactors")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Factori pentru energie</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("energyEmissionFactors")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Factori pentru inputuri</label>
              <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("inputEmissionFactors")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Preț certificat (€/tCO2e)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("pricePerTonneEUR")} />
            </div>
          </div>
        );
      case 7:
        return (
          <div className="space-y-8">
            {/* Cantități produse */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Cantități produse</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tonaje (t)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionTonnage")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Volume (m³)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionVolume")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Calendarul producției</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionCalendar")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Sezoane</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionSeasons")} />
                </div>
              </div>
            </div>

            {/* Tipuri de producție */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Tipuri de producție</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Producție verde</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionTypeGreen")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Procesare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionTypeProcessing")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Materie primă</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("productionTypeRawMaterial")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Finisare/ambalaj</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("finishingPackaging")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Distribuție</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("distribution")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 8:
        return (
          <div className="space-y-8">
            {/* Costuri operaționale */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Costuri operaționale</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Costuri energie (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("energyCosts")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Costuri combustibili (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fuelCosts")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Costuri fertilizanți (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("fertilizerCosts")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Prețuri de vânzare (€/t)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("sellingPrices")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Marje (€/t)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("margins")} />
                </div>
              </div>
            </div>

            {/* Costuri tranziție */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Costuri tranziție</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Tehnologii (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("transitionCostsTechnology")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Echipamente verzi (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("transitionCostsGreenEquipment")} />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-2">Modernizare (€)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("transitionCostsModernization")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 9:
        return (
          <div className="space-y-8">
            {/* Climă și irigare */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Climă și irigare</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Calendar/regimul de irigare</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("irrigationCalendar")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Climă locală</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("localClimate")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Temperaturi</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("temperatureData")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Precipitații</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("precipitationData")} />
                </div>
              </div>
            </div>

            {/* Management deșeuri */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Management deșeuri</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Management deșeuri agricole</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("agriculturalWasteManagement")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Management reziduuri</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("residueManagement")} />
                </div>
              </div>
            </div>

            {/* Personal și transport */}
            <div>
              <h4 className="text-lg font-semibold text-emerald-700 mb-4">Personal și transport</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Ore de muncă (anual)</label>
                  <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("workingHours")} />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Transport personal</label>
                  <input className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("personalTransport")} />
                </div>
              </div>
            </div>
          </div>
        );
      case 10:
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Reducere N (%)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("project_reductionN_pct")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Creștere energie verde (%)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("project_greenEnergy_pct")} />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Lucrare sol (proiect)</label>
              <select className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("project_tillage")}>
                <option value="plough">Arat</option>
                <option value="min_till">Min-till</option>
                <option value="no_till">No-till</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Cover crops proiect (ha)</label>
              <input type="number" className="w-full rounded-lg border border-gray-300 p-3 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" {...register("project_coverCropsHa")} />
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  const onSubmit = (v: FormValues) => {
    const baseline: Scenario = {
      // 1. Date de bază despre organizație/firma
      org: {
        name: v.name,
        location: v.location,
        activityDomain: v.activityDomain,
        cultivatedAreaHa: v.cultivatedAreaHa,
        cropTypes: v.cropTypes,
        animalCount: v.animalCount,
        infrastructure: v.infrastructure,
      },
      // 2. Consum de energie (electricitate, combustibili)
      energy: {
        electricityKWh: v.electricityKWh,
        renewableSharePct: v.renewableSharePct,
        fuels: [
          { type: "diesel", amount: v.dieselL, unit: "L" },
          { type: "gasoline", amount: v.gasolineL, unit: "L" },
        ],
      },
      // 3. Utilizarea inputurilor agricole
      agri: {
        fertilizerN_Kg: v.fertilizerN_Kg,
        fertilizerN_Type: v.fertilizerN_Type,
        fertilizerP2O5_Kg: v.fertilizerP2O5_Kg,
        fertilizerP_Type: v.fertilizerP_Type,
        fertilizerK2O_Kg: v.fertilizerK2O_Kg,
        fertilizerK_Type: v.fertilizerK_Type,
        pesticideType: v.pesticideType,
        pesticideDosePerHa: v.pesticideDosePerHa,
        pesticideApplicationsPerSeason: v.pesticideApplicationsPerSeason,
        seedType: v.seedType,
        importSharePct: v.importSharePct,
      },
      // 4. Managementul terenului și solului
      land: {
        soilType: v.soilType,
        previousUse: v.previousUse,
        irrigationM3: v.irrigationM3,
        drainage: v.drainage,
        tillage: v.tillage as Tillage,
        agroforestry: v.agroforestry,
        coverCropsHa: v.coverCropsHa,
        erosionDegradationNotes: v.erosionDegradationNotes,
        soilFertilityNotes: v.soilFertilityNotes,
      },
      // 5. Transporte și lanț de aprovizionare
      transport: {
        internalTransport: {
          distances: v.internalTransportDistances,
          vehicleType: v.internalTransportVehicleType,
          frequency: v.internalTransportFrequency,
        },
        inputTransport: {
          fuelTransport: v.inputTransportFuel,
          seedTransport: v.inputTransportSeeds,
          chemicalInputsTransport: v.inputTransportChemicals,
        },
        exportCollection: {
          productionExport: v.exportCollectionProduction,
        },
        storageProcessing: {
          storage: v.storageProcessingStorage,
          processing: v.storageProcessingProcessing,
          packaging: v.storageProcessingPackaging,
          equipment: v.storageProcessingEquipment,
          energyConsumed: v.storageProcessingEnergyConsumed,
        },
      },
      // 6. Emisii directe și indirecte
      emissions: {
        directEmissions: {
          onSiteEngines: v.onSiteEngines,
          onSiteGenerators: v.onSiteGenerators,
          onSiteEquipment: v.onSiteEquipment,
        },
        indirectEmissions: {
          importedElectricity: v.importedElectricity,
          heating: v.heating,
        },
        fertilizerPesticideEmissions: {
          fertilizerEmissions: v.fertilizerEmissions,
          pesticideEmissions: v.pesticideEmissions,
          lcaModels: v.lcaModels,
        },
      },
      // 7. Factori de emisie (emission factors)
      factors,
      // 8. Date despre producție / output
      production: {
        quantities: {
          tonnage: v.productionTonnage,
          volume: v.productionVolume,
        },
        productionCalendar: {
          annual: v.productionCalendar,
          seasons: v.productionSeasons,
        },
        productionType: {
          green: v.productionTypeGreen,
          processing: v.productionTypeProcessing,
          rawMaterial: v.productionTypeRawMaterial,
        },
        finishingDistribution: {
          finishing: v.finishingPackaging,
          packaging: v.finishingPackaging,
          distribution: v.distribution,
        },
      },
      // 9. Date financiare relevante
      financial: {
        inputCosts: {
          energyCosts: v.energyCosts,
          fuelCosts: v.fuelCosts,
          fertilizerCosts: v.fertilizerCosts,
        },
        salesPrices: {
          sellingPrices: v.sellingPrices,
          margins: v.margins,
        },
        transitionCosts: {
          technologyInvestments: v.transitionCostsTechnology,
          greenEquipment: v.transitionCostsGreenEquipment,
          modernization: v.transitionCostsModernization,
        },
      },
      // 10. Alte date auxiliare
      auxiliary: {
        irrigationClimate: {
          irrigationCalendar: v.irrigationCalendar,
          localClimate: v.localClimate,
          temperatureData: v.temperatureData,
          precipitationData: v.precipitationData,
        },
        wasteManagement: {
          agriculturalWaste: v.agriculturalWasteManagement,
          residues: v.residueManagement,
        },
        personnelData: {
          workingHours: v.workingHours,
          personalTransport: v.personalTransport,
        },
      },
      pricePerTonneEUR: v.pricePerTonneEUR,
    };

    const project: Scenario = {
      ...baseline,
      // Modificări pentru scenariul proiect
      energy: {
        ...baseline.energy,
        renewableSharePct: Math.min(100, v.renewableSharePct + v.project_greenEnergy_pct),
        fuels: [
          { type: "diesel", amount: v.dieselL * (v.project_tillage === "no_till" ? 0.7 : 1), unit: "L" },
          { type: "gasoline", amount: v.gasolineL, unit: "L" },
        ],
      },
      agri: {
        ...baseline.agri,
        fertilizerN_Kg: v.fertilizerN_Kg * (1 - v.project_reductionN_pct / 100),
      },
      land: {
        ...baseline.land,
        tillage: v.project_tillage as Tillage,
        coverCropsHa: v.project_coverCropsHa,
      },
    };

    const calculationResult = compareScenarios(baseline, project);
    setResult(calculationResult);
    
    // Salvează raportul în baza de date
    saveReportToDatabase(v, calculationResult);
  };

  const saveReportToDatabase = async (formData: FormValues, results: ReturnType<typeof compareScenarios>) => {
    if (!user) {
      setSaveMessage('Trebuie să fiți autentificat pentru a salva raportul');
      return;
    }

    setSaving(true);
    setSaveMessage(null);

    try {
      const token = localStorage.getItem('auth_token');
      if (!token) {
        setSaveMessage('Token de autentificare lipsă');
        return;
      }

      // Generează numele raportului
      const reportNumber = Math.floor(Math.random() * 1000) + 1;
      const reportName = `Raport ${reportNumber} ${formData.name}`;
      const reportTitle = `Raport de emisii - ${formData.name} (${formData.location})`;

      const response = await apiClient.createReport({
        name: reportName,
        title: reportTitle,
        data: formData,
        results: {
          totalEmissionsBaseline: results.baseline.total,
          totalEmissionsProject: results.project.total,
          emissionReduction: results.delta,
          costSavings: results.revenueEUR,
          paybackPeriod: 0, // Not calculated in current version
          hotspots: {
            baseline: results.baseline.hotspots,
            project: results.project.hotspots,
          },
        },
      }, token);

      if (response.data && 'report' in response.data) {
        setSaveMessage('Raportul a fost salvat cu succes!');
        setSavedReportId((response.data as { report: { id: string } }).report.id);
      } else {
        setSaveMessage(response.error || 'A apărut o eroare la salvarea raportului');
        setSavedReportId(null);
      }
    } catch (error) {
      console.error('Error saving report:', error);
      setSaveMessage('A apărut o eroare de rețea la salvarea raportului');
      setSavedReportId(null);
    } finally {
      setSaving(false);
    }
  };

  // const printRef = useRef<HTMLDivElement>(null);

  return (
    <ProtectedRoute>
      <div className="mx-auto max-w-5xl p-6">
        <h2 className="text-2xl font-semibold text-emerald-800">EcoScope - Calculator emisii</h2>


        {/* Link către rapoartele mele */}
        <div className="mt-4">
          <Link
            href="/my-reports"
            className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            Rapoartele mele
          </Link>
        </div>

        {/* Progress indicator */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
        <div>
              <h3 className="text-lg font-semibold text-emerald-800">
                {SLIDES[currentSlide].title}
              </h3>
              <p className="text-sm text-gray-600">
                {SLIDES[currentSlide].description}
              </p>
        </div>
            <div className="text-sm text-gray-500">
              {currentSlide + 1} din {SLIDES.length}
        </div>
        </div>

          {/* Progress bar */}
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-emerald-600 h-2 rounded-full transition-all duration-300"
              style={{ width: `${((currentSlide + 1) / SLIDES.length) * 100}%` }}
            ></div>
        </div>

          {/* Slide indicators */}
          <div className="flex justify-center mt-4 space-x-2">
            {SLIDES.map((_, index) => (
              <button
                key={index}
                onClick={() => goToSlide(index)}
                className={`w-3 h-3 rounded-full transition-colors ${
                  index === currentSlide 
                    ? 'bg-emerald-600' 
                    : index < currentSlide 
                      ? 'bg-emerald-300' 
                      : 'bg-gray-300'
                }`}
              />
            ))}
        </div>
        </div>

        {/* Form content */}
        <form onSubmit={handleSubmit(onSubmit)} className="mt-6">
          <div className="card border border-color rounded-xl p-6 shadow max-w-4xl mx-auto">
            {renderSlide(currentSlide)}
        </div>

          {/* Navigation buttons */}
          <div className="flex justify-between items-center mt-6">
            <button
              type="button"
              onClick={prevSlide}
              disabled={currentSlide === 0}
              className="flex items-center px-4 py-2 text-gray-600 hover:text-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              Anterior
            </button>

            <div className="flex space-x-2">
              {currentSlide === SLIDES.length - 1 ? (
          <button 
                  type="button"
                  onClick={handleSubmit(onSubmit)}
                  className="flex items-center px-6 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={saving}
          >
                  {saving ? 'Se salvează...' : 'Finalizează raportul'}
                  <svg className="w-5 h-5 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
          </button>
              ) : (
                <button
                  type="button"
                  onClick={nextSlide}
                  className="flex items-center px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700"
                >
                  Următorul
                  <svg className="w-5 h-5 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              )}
        </div>
          </div>
        </form>

        {/* Mesaj de salvare - sub buton */}
        {saveMessage && (
          <div className={`mt-4 p-4 rounded-lg ${
            saveMessage.includes('succes') 
              ? 'bg-green-50 border border-green-200 text-green-700' 
              : 'bg-red-50 border border-red-200 text-red-700'
          }`}>
            <div className="flex items-start">
              {saveMessage.includes('succes') ? (
                <svg className="w-5 h-5 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                <svg className="w-5 h-5 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              )}
              <div className="flex-1">
                <p className="mb-2">{saveMessage}</p>
                {savedReportId && (
                  <div className="mt-3">
                    <p className="text-sm mb-2">Iată raportul vostru:</p>
                      <Link
                        href={`/reports/${savedReportId}`}
                      className="inline-flex items-center px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                      >
                      <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Vezi raportul
                      </Link>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
        
        {/* Rezultatele calculului */}
        {result && (
          <div className="mt-8">
            <h2 className="text-2xl font-semibold text-emerald-800 mb-4">
              Rezultatele calculului
            </h2>
            <BarChart
              labels={["Baseline", "Proiect"]}
              baseline={[result.baseline.total]}
              project={[result.project.total]}
              title="Emisii CO2 (tCO2e/an)"
            />
        </div>
      )}
          </div>
    </ProtectedRoute>
  );
}
