"use client";

import { useState, useEffect, useRef } from 'react';
import { useParams } from 'next/navigation';
// import { useAuth } from '@/contexts/AuthContext';
import { apiClient } from '@/lib/api';
import ProtectedRoute from '@/components/ProtectedRoute';
import Link from 'next/link';
// import { BarChart } from '@/components/BarChart';
import { useReactToPrint } from 'react-to-print';

interface ReportData {
  id: string;
  name: string;
  title: string;
  data: Record<string, unknown>;
  results?: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

export default function ReportViewPage() {
  // const { user } = useAuth();
  const params = useParams();
  const [report, setReport] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const printRef = useRef<HTMLDivElement>(null);
  const handlePrint = useReactToPrint({ contentRef: printRef });

  useEffect(() => {
    const fetchReport = async () => {
      try {
        const token = localStorage.getItem('auth_token');
        if (!token) {
          setError('Nu sunteți autentificat');
          return;
        }

        const response = await apiClient.getReport(params.id as string, token);
        if (response.data && typeof response.data === 'object' && 'report' in response.data) {
          setReport((response.data as { report: ReportData }).report);
        } else {
          setError(response.error || 'A apărut o eroare la încărcarea raportului');
        }
      } catch (error) {
        console.error('Error fetching report:', error);
        setError('A apărut o eroare de rețea');
      } finally {
        setLoading(false);
      }
    };

    if (params.id) {
      fetchReport();
    }
  }, [params.id]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ro-RO', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const formatValue = (value: unknown, key?: string): string => {
    if (typeof value === 'number') {
      // Formatare specială pentru anumite câmpuri
      if (key?.includes('Pct') || key?.includes('pct')) {
        return `${value}%`;
      }
      if (key?.includes('Ha') || key?.includes('ha')) {
        return `${value.toLocaleString('ro-RO')} ha`;
      }
      if (key?.includes('Kg') || key?.includes('kg')) {
        return `${value.toLocaleString('ro-RO')} kg`;
      }
      if (key?.includes('L') || key?.includes('l')) {
        return `${value.toLocaleString('ro-RO')} L`;
      }
      if (key?.includes('KWh') || key?.includes('kWh')) {
        return `${value.toLocaleString('ro-RO')} kWh`;
      }
      if (key?.includes('M3') || key?.includes('m3')) {
        return `${value.toLocaleString('ro-RO')} m³`;
      }
      if (key?.includes('EUR') || key?.includes('Costs') || key?.includes('Prices')) {
        return `${value.toLocaleString('ro-RO')} EUR`;
      }
      if (key?.includes('Hours') || key?.includes('hours')) {
        return `${value.toLocaleString('ro-RO')} ore`;
      }
      return value.toLocaleString('ro-RO');
    }
    if (typeof value === 'boolean') {
      return value ? 'Da' : 'Nu';
    }
    if (Array.isArray(value)) {
      return value.join(', ');
    }
    if (typeof value === 'object' && value !== null) {
      return JSON.stringify(value, null, 2);
    }
    return String(value || '-');
  };

  const getHotspotLabel = (key: string) => {
    const labels: Record<string, string> = {
      energy: 'Energie',
      inputs: 'Inputuri',
      transport: 'Transport',
      irrigation: 'Irigare',
      processing: 'Procesare',
      waste: 'Deșeuri',
      soil: 'Sol',
    };
    return labels[key] || key;
  };

  const getResultLabel = (key: string) => {
    const labels: Record<string, string> = {
      totalEmissionsBaseline: 'Emisii totale (scenariul de bază)',
      totalEmissionsProject: 'Emisii totale (scenariul proiect)',
      emissionReduction: 'Reducerea emisiilor',
      costSavings: 'Economii costuri',
      paybackPeriod: 'Perioada de rambursare',
    };
    return labels[key] || key.replace(/([A-Z])/g, ' $1').trim();
  };

  const getFieldLabel = (key: string) => {
    const labels: Record<string, string> = {
      // Date de bază
      name: 'Denumire',
      location: 'Locație',
      activityDomain: 'Domeniu de activitate',
      cultivatedAreaHa: 'Suprafață cultivată (ha)',
      cropTypes: 'Tipuri de culturi',
      animalCount: 'Număr animale',
      infrastructure: 'Infrastructură',
      
      // Energie
      electricityKWh: 'Electricitate (kWh)',
      renewableSharePct: 'Procent energie regenerabilă',
      dieselL: 'Motorină (L)',
      gasolineL: 'Benzină (L)',
      energyCosts: 'Costuri energie',
      fuelCosts: 'Costuri combustibili',
      
      // Inputuri agricole
      fertilizerN_Kg: 'Îngrășământ Azot (kg)',
      fertilizerN_Type: 'Tip îngrășământ Azot',
      fertilizerP2O5_Kg: 'Îngrășământ Fosfor (kg)',
      fertilizerP_Type: 'Tip îngrășământ Fosfor',
      fertilizerK2O_Kg: 'Îngrășământ Potasiu (kg)',
      fertilizerK_Type: 'Tip îngrășământ Potasiu',
      fertilizerCosts: 'Costuri îngrășăminte',
      pesticideType: 'Tip pesticid',
      pesticideDosePerHa: 'Doza per hectar',
      pesticideApplicationsPerSeason: 'Aplicații per sezon',
      seedType: 'Tip semințe',
      importSharePct: 'Procent import',
      
      // Management teren
      soilType: 'Tip sol',
      previousUse: 'Utilizare precedentă',
      irrigationM3: 'Irigare (m³)',
      drainage: 'Drenaj',
      tillage: 'Lucrare sol',
      agroforestry: 'Agroforestry',
      coverCropsHa: 'Culturi de acoperire (ha)',
      erosionDegradationNotes: 'Note eroziune',
      soilFertilityNotes: 'Note fertilitate sol',
      
      // Transport
      internalTransportDistances: 'Distanțe transport intern',
      internalTransportVehicleType: 'Tip vehicul transport intern',
      internalTransportFrequency: 'Frecvență transport intern',
      inputTransportFuel: 'Transport combustibili',
      inputTransportSeeds: 'Transport semințe',
      inputTransportChemicals: 'Transport inputuri chimice',
      exportCollectionProduction: 'Export/colectare producție',
      personalTransport: 'Transport personal',
      
      // Depozitare și procesare
      storageProcessingStorage: 'Depozitare',
      storageProcessingProcessing: 'Procesare',
      storageProcessingPackaging: 'Ambalare',
      storageProcessingEquipment: 'Utilaje',
      storageProcessingEnergyConsumed: 'Energie consumată',
      finishingPackaging: 'Finisare/ambalaj',
      
      // Emisii
      onSiteEngines: 'Motoare la fața locului',
      onSiteGenerators: 'Generatoare',
      onSiteEquipment: 'Echipamente',
      importedElectricity: 'Electricitate importată',
      heating: 'Încălzire',
      fertilizerEmissions: 'Emisii din fertilizanți',
      pesticideEmissions: 'Emisii din pesticide',
      lcaModels: 'Modele LCA',
      
      // Factori de emisie
      emissionFactorsLocalized: 'Factori localizați',
      emissionFactorsGeneric: 'Factori generici',
      fuelEmissionFactors: 'Factori combustibili',
      energyEmissionFactors: 'Factori energie',
      inputEmissionFactors: 'Factori inputuri',
      pricePerTonneEUR: 'Preț per tonă CO₂ (EUR)',
      
      // Producție
      productionTonnage: 'Cantitate produsă (tone)',
      productionVolume: 'Volum producție',
      productionCalendar: 'Calendar producție',
      productionSeasons: 'Sezoane producție',
      productionTypeGreen: 'Tip producție verde',
      productionTypeProcessing: 'Tip procesare',
      productionTypeRawMaterial: 'Materie primă',
      
      // Personal și muncă
      workingHours: 'Ore de muncă',
      margins: 'Marje',
      distribution: 'Distribuție',
      sellingPrices: 'Prețuri vânzare',
      
      // Clima și mediu
      localClimate: 'Climă locală',
      temperatureData: 'Date temperatură',
      precipitationData: 'Date precipitații',
      irrigationCalendar: 'Calendar irigare',
      
      // Management deșeuri
      residueManagement: 'Management reziduuri',
      agriculturalWasteManagement: 'Management deșeuri agricole',
      
      // Costuri tranziție
      transitionCostsTechnology: 'Costuri tehnologie',
      transitionCostsModernization: 'Costuri modernizare',
      transitionCostsGreenEquipment: 'Costuri echipamente verzi',
      
      // Proiect
      project_reductionN_pct: 'Reducere Azot (%)',
      project_greenEnergy_pct: 'Energie verde (%)',
      project_tillage: 'Lucrare sol proiect',
      project_coverCropsHa: 'Culturi acoperire proiect (ha)',
    };
    return labels[key] || key.replace(/([A-Z])/g, ' $1').trim();
  };

  const formatResultValue = (key: string, value: unknown) => {
    if (typeof value === 'number') {
      switch (key) {
        case 'totalEmissionsBaseline':
        case 'totalEmissionsProject':
        case 'emissionReduction':
          return `${value.toFixed(2)} tCO₂e`;
        case 'costSavings':
          return `${value.toFixed(2)} EUR`;
        case 'paybackPeriod':
          return value === 0 ? 'Nu se aplică' : `${value.toFixed(1)} ani`;
        default:
          return value.toLocaleString('ro-RO');
      }
    }
    return formatValue(value);
  };

  if (loading) {
    return (
      <ProtectedRoute>
        <div className="mx-auto max-w-6xl p-6">
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div>
            <span className="ml-3 text-gray-600">Se încarcă raportul...</span>
          </div>
        </div>
      </ProtectedRoute>
    );
  }

  if (error) {
    return (
      <ProtectedRoute>
        <div className="mx-auto max-w-6xl p-6">
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <div className="flex">
              <svg className="w-5 h-5 text-red-400 mr-2" 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>
              <p className="text-red-700">{error}</p>
            </div>
          </div>
          <Link
            href="/my-reports"
            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-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            Înapoi la rapoarte
          </Link>
        </div>
      </ProtectedRoute>
    );
  }

  if (!report) {
    return (
      <ProtectedRoute>
        <div className="mx-auto max-w-6xl p-6">
          <div className="text-center py-12">
            <h3 className="text-lg font-medium text-gray-900 mb-2">Raportul nu a fost găsit</h3>
            <p className="text-gray-500 mb-4">
              Raportul pe care îl căutați nu există sau nu aveți permisiunea să îl vizualizați.
            </p>
            <Link
              href="/my-reports"
              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-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              Înapoi la rapoarte
            </Link>
          </div>
        </div>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <div className="mx-auto max-w-6xl p-6">
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h1 className="text-3xl font-bold text-emerald-800 mb-2">
                {report.name}
              </h1>
              <p className="text-gray-600">
                {report.title}
              </p>
            </div>
            <div className="flex space-x-2">
              <button
                onClick={handlePrint}
                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="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                Export PDF
              </button>
              <Link
                href={`/wizard?edit=${report.id}`}
                className="inline-flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
                Editează
              </Link>
              <Link
                href="/my-reports"
                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-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                Înapoi la rapoarte
              </Link>
            </div>
          </div>
          
          <div className="text-sm text-gray-500">
            <p>Creat: {formatDate(report.createdAt)}</p>
            {report.updatedAt !== report.createdAt && (
              <p>Actualizat: {formatDate(report.updatedAt)}</p>
            )}
          </div>
        </div>

        {/* Conținutul raportului pentru exportare PDF */}
        <div ref={printRef}>

        {/* Rezultate calcule */}
        {report.results && (
          <div className="mb-8">
            <h2 className="text-2xl font-semibold text-emerald-800 mb-4">
              Rezultate calcule emisii
            </h2>
            <div className="bg-white rounded-lg border border-gray-200 p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {Object.entries(report.results).map(([key, value]) => {
                  // Handle nested objects like hotspots
                  if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
                    // Special handling for hotspots
                    if (key === 'hotspots') {
                      return (
                        <div key={key} className="bg-gray-50 rounded-lg p-6 col-span-full">
                          <h3 className="font-medium text-gray-900 mb-6 text-lg">
                            Hotspots de emisii
                          </h3>
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            {((value as Record<string, unknown>).baseline as Record<string, unknown>) && (
                              <div className="bg-white rounded-lg p-4 border border-gray-200">
                                <h4 className="text-md font-semibold text-gray-800 mb-4 flex items-center">
                                  <span className="w-3 h-3 bg-red-500 rounded-full mr-2"></span>
                                  Scenariul de bază
                                </h4>
                                <div className="space-y-3">
                                  {Object.entries((value as Record<string, unknown>).baseline as Record<string, unknown>).map(([subKey, subValue]) => (
                                    <div key={subKey} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-b-0">
                                      <span className="text-sm font-medium text-gray-700 capitalize">
                                        {getHotspotLabel(subKey)}
                                      </span>
                                      <span className="text-sm font-semibold text-gray-900">
                                        {typeof subValue === 'number' ? `${subValue.toFixed(2)} tCO₂e` : formatValue(subValue, subKey)}
                                      </span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                            
                            {((value as Record<string, unknown>).project as Record<string, unknown>) && (
                              <div className="bg-white rounded-lg p-4 border border-gray-200">
                                <h4 className="text-md font-semibold text-gray-800 mb-4 flex items-center">
                                  <span className="w-3 h-3 bg-green-500 rounded-full mr-2"></span>
                                  Scenariul proiect
                                </h4>
                                <div className="space-y-3">
                                  {Object.entries((value as Record<string, unknown>).project as Record<string, unknown>).map(([subKey, subValue]) => (
                                    <div key={subKey} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-b-0">
                                      <span className="text-sm font-medium text-gray-700 capitalize">
                                        {getHotspotLabel(subKey)}
                                      </span>
                                      <span className="text-sm font-semibold text-gray-900">
                                        {typeof subValue === 'number' ? `${subValue.toFixed(2)} tCO₂e` : formatValue(subValue, subKey)}
                                      </span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      );
                    }
                    
                    // Default handling for other nested objects
                    return (
                      <div key={key} className="bg-gray-50 rounded-lg p-4 col-span-full">
                        <h3 className="font-medium text-gray-900 mb-4 capitalize">
                          {key.replace(/([A-Z])/g, ' $1').trim()}
                        </h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          {Object.entries(value).map(([subKey, subValue]) => (
                            <div key={subKey} className="bg-white rounded p-3">
                              <h4 className="text-sm font-medium text-gray-700 mb-1 capitalize">
                                {subKey.replace(/([A-Z])/g, ' $1').trim()}
                              </h4>
                              <p className="text-lg font-semibold text-emerald-600">
                                {formatValue(subValue, subKey)}
                              </p>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  }
                  
                  return (
                    <div key={key} className="bg-gray-50 rounded-lg p-4">
                      <h3 className="font-medium text-gray-900 mb-2 capitalize">
                        {getResultLabel(key)}
                      </h3>
                      <p className="text-2xl font-bold text-emerald-600">
                        {formatResultValue(key, value)}
                      </p>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {/* Date formular */}
        <div className="mb-8">
          <h2 className="text-2xl font-semibold text-emerald-800 mb-4">
            Date raport
          </h2>
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {Object.entries(report.data).map(([key, value]) => (
                <div key={key} className="border-b border-gray-100 pb-2">
                  <dt className="text-sm font-medium text-gray-500">
                    {getFieldLabel(key)}
                  </dt>
                  <dd className="mt-1 text-sm text-gray-900">
                    {formatValue(value, key)}
                  </dd>
                </div>
              ))}
            </div>
          </div>
        </div>
        </div> {/* Închidere div pentru print */}
      </div>
    </ProtectedRoute>
  );
}
