import React, { useState, useEffect } from 'react';
import {Plant, PlantStatistics, HarvestRecord, MaintenanceRecord, HarvestUnits} from '../types';
import { BarChart3, TrendingUp, Calendar, Award, X  } from 'lucide-react';

interface PlantStatisticsProps {
  plant: Plant;
  harvestRecords: HarvestRecord[];
  maintenanceRecords: MaintenanceRecord[];
  onClose: () => void;
}

const PlantStatisticsComponent: React.FC<PlantStatisticsProps> = ({
  plant,
  harvestRecords,
  maintenanceRecords,
  onClose
}) => {
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [statistics, setStatistics] = useState<PlantStatistics | null>(null);

  // Get harvests for the selected year
  const yearHarvests = harvestRecords.filter(h =>
      h.plantId === plant.id && new Date(h.date).getFullYear() === selectedYear
  );

  const availableYears = Array.from(
    new Set([
      new Date(plant.plantingDate).getFullYear(),
      ...harvestRecords.map(h => new Date(h.date).getFullYear()),
      ...maintenanceRecords.map(m => new Date(m.date).getFullYear()),
      new Date().getFullYear()
    ])
  ).sort((a, b) => b - a);

  useEffect(() => {
    calculateStatistics();
  }, [selectedYear, plant, harvestRecords, maintenanceRecords]);

  const calculateStatistics = () => {
    const yearMaintenance = maintenanceRecords.filter(m =>
      m.plantId === plant.id && new Date(m.date).getFullYear() === selectedYear
    );

    const totalHarvest = yearHarvests.reduce((sum, h) => sum + h.quantity, 0);
    
    const maintenanceCount = {
      chemical: yearMaintenance.filter(m => m.type === 'chemical').length,
      fertilizer: yearMaintenance.filter(m => m.type === 'fertilizer').length,
      watering: yearMaintenance.filter(m => m.type === 'watering').length,
      pruning: yearMaintenance.filter(m => m.type === 'pruning').length,
    };

    const heightGrowth = plant.currentHeight && plant.seedlingHeight 
      ? plant.currentHeight - plant.seedlingHeight 
      : 0;

    setStatistics({
      plantId: plant.id,
      year: selectedYear,
      bloomingDates: [], // Would come from plant history
      fruitingDates: [], // Would come from plant history
      harvestDates: yearHarvests.map(h => h.date),
      totalHarvest,
      heightGrowth,
      maintenanceCount,
      completedTasks: yearMaintenance.filter(m => m.isCompleted).length,
      plannedTasks: yearMaintenance.filter(m => m.isPlanned).length
    });
  };

  // Prepare chart data
  const prepareChartData = () => {
    if (yearHarvests.length === 0) return [];

    // Group harvests by date and sum quantities
    const harvestsByDate = yearHarvests.reduce((acc, harvest) => {
      const date = harvest.date;
      if (!acc[date]) {
        acc[date] = { date, quantity: 0, unit: harvest.unit };
      }
      acc[date].quantity += harvest.quantity;
      return acc;
    }, {} as Record<string, { date: string; quantity: number; unit: string }>);

    // Convert to array and sort by date
    return Object.values(harvestsByDate).sort((a, b) =>
        new Date(a.date).getTime() - new Date(b.date).getTime()
    );
  };

  const chartData = prepareChartData();
  const maxQuantity = Math.max(...chartData.map(d => d.quantity), 0);

  if (!statistics) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center p-6 border-b border-gray-200">
          <div>
            <h3 className="text-xl font-semibold text-gray-900">
              {plant.variety} - Статистика
            </h3>
            <p className="text-sm text-gray-600">Год: {selectedYear}</p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="h-6 w-6" />
          </button>
        </div>

        <div className="p-6">
          {/* Year Selector */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Выбор года
            </label>
            <select
              value={selectedYear}
              onChange={(e) => setSelectedYear(parseInt(e.target.value))}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
            >
              {availableYears.map(year => (
                <option key={year} value={year}>{year}</option>
              ))}
            </select>
          </div>

          {/* Statistics Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div className="bg-green-50 p-4 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-green-600">Общий урожай</p>
                  <p className="text-2xl font-bold text-green-800">
                    {statistics.totalHarvest.toFixed(1)}
                  </p>
                </div>
                <Award className="h-8 w-8 text-green-600" />
              </div>
            </div>

            <div className="bg-blue-50 p-4 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600">Прирост</p>
                  <p className="text-2xl font-bold text-blue-800">
                    +{statistics.heightGrowth.toFixed(1)} м
                  </p>
                </div>
                <TrendingUp className="h-8 w-8 text-blue-600" />
              </div>
            </div>

            <div className="bg-purple-50 p-4 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-purple-600">Сборов урожая</p>
                  <p className="text-2xl font-bold text-purple-800">
                    {statistics.harvestDates.length}
                  </p>
                </div>
                <Calendar className="h-8 w-8 text-purple-600" />
              </div>
            </div>

            <div className="bg-orange-50 p-4 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-orange-600">Работы</p>
                  <p className="text-2xl font-bold text-orange-800">
                    {Object.values(statistics.maintenanceCount).reduce((a, b) => a + b, 0)}
                  </p>
                </div>
                <BarChart3 className="h-8 w-8 text-orange-600" />
              </div>
            </div>
          </div>

          {/* Maintenance Breakdown */}
          <div className="bg-gray-50 p-6 rounded-lg mb-6">
            <h4 className="text-lg font-semibold text-gray-900 mb-4">Выполненные работы</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <p className="text-2xl font-bold text-red-600">{statistics.maintenanceCount.chemical}</p>
                <p className="text-sm text-gray-600">Обработано химикатами</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-green-600">{statistics.maintenanceCount.fertilizer}</p>
                <p className="text-sm text-gray-600">Внесено удобрений</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-blue-600">{statistics.maintenanceCount.watering}</p>
                <p className="text-sm text-gray-600">Полито</p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-yellow-600">{statistics.maintenanceCount.pruning}</p>
                <p className="text-sm text-gray-600">Обрезано</p>
              </div>
            </div>
          </div>

          {/* Ripening Information */}
          {(plant.estimatedRipeningStart || plant.estimatedRipeningEnd || plant.ripeningNotes) && (
              <div className="bg-yellow-50 p-6 rounded-lg mb-6">
                <h4 className="text-lg font-semibold text-gray-900 mb-4">Информация о созревании</h4>
                <div className="space-y-3">
                  {(plant.estimatedRipeningStart || plant.estimatedRipeningEnd) && (
                      <div>
                        <p className="text-sm font-medium text-yellow-800 mb-2">Estimated Ripening Period:</p>
                        <div className="flex items-center space-x-4">
                          {plant.estimatedRipeningStart && (
                              <div className="text-center">
                                <p className="text-lg font-bold text-yellow-700">Day {plant.estimatedRipeningStart}</p>
                                <p className="text-xs text-yellow-600">
                                  {new Date(selectedYear, 0, plant.estimatedRipeningStart).toLocaleDateString('en-US', {
                                    month: 'short',
                                    day: 'numeric'
                                  })}
                                </p>
                              </div>
                          )}
                          {plant.estimatedRipeningStart && plant.estimatedRipeningEnd && (
                              <span className="text-yellow-600">→</span>
                          )}
                          {plant.estimatedRipeningEnd && (
                              <div className="text-center">
                                <p className="text-lg font-bold text-yellow-700">Day {plant.estimatedRipeningEnd}</p>
                                <p className="text-xs text-yellow-600">
                                  {new Date(selectedYear, 0, plant.estimatedRipeningEnd).toLocaleDateString('en-US', {
                                    month: 'short',
                                    day: 'numeric'
                                  })}
                                </p>
                              </div>
                          )}
                        </div>
                      </div>
                  )}
                  {plant.ripeningNotes && (
                      <div>
                        <p className="text-sm font-medium text-yellow-800 mb-1">Notes:</p>
                        <p className="text-sm text-yellow-700">{plant.ripeningNotes}</p>
                      </div>
                  )}
                </div>
              </div>
          )}

          {/* Harvest Timeline */}
          {harvestRecords.some(h => h.plantId === plant.id && new Date(h.date).getFullYear() === selectedYear) && (
            <div className="bg-green-50 p-6 rounded-lg">
              <h4 className="text-lg font-semibold text-gray-900 mb-4">График сбора урожая</h4>
              <div className="space-y-4">
                {(() => {
                  // 1. Берём только урожай этого растения за выбранный год
                  const plantHarvests = harvestRecords.filter(
                    h => h.plantId === plant.id && new Date(h.date).getFullYear() === selectedYear
                  );

                  // 2. Группируем по дате
                  const groupedByDate = plantHarvests.reduce<Record<string, HarvestRecord[]>>((acc, harvest) => {
                    if (!acc[harvest.date]) {
                      acc[harvest.date] = [];
                    }
                    acc[harvest.date].push(harvest);
                    return acc;
                  }, {});

                  // 3. Сортируем даты:
                  // если даты разные — по дате (новее выше),
                  // если совпадают — по id (новее выше)
                  const sortedDates = Object.keys(groupedByDate).sort((a, b) => {
                    const dateA = new Date(a).getTime();
                    const dateB = new Date(b).getTime();

                    if (dateA !== dateB) {
                      return dateB - dateA;
                    }

                    // если даты одинаковые, сравним максимальный id внутри группы
                    const maxIdA = Math.max(...groupedByDate[a].map(h => h.id));
                    const maxIdB = Math.max(...groupedByDate[b].map(h => h.id));
                    return maxIdB - maxIdA;
                  });

                  // 4. Рендерим
                  return sortedDates.map(date => (
                    <div key={date} className="bg-white rounded-lg border border-green-100 p-4">
                      <h5 className="text-md font-medium text-gray-900 mb-2">
                        {new Date(date).toLocaleDateString()}
                      </h5>
                      <div className="space-y-2">
                        {groupedByDate[date]
                          .sort((a, b) => b.id - a.id) // внутри даты тоже сортируем по id
                          .map(harvest => (
                            <div
                              key={harvest.id}
                              className="py-2 px-3 bg-green-50 rounded border border-green-100"
                            >
                              <div className="flex justify-between items-start">
                                <span className="text-sm font-medium text-green-700">
                                  {harvest.quantity} {HarvestUnits[harvest.unit || ""]}
                                  {harvest?.weight && (
                                      <div className="text-xs text-gray-500">
                                        ({harvest.weight} {harvest.weightUnit})
                                      </div>
                                  )}
                                </span>
                              </div>
                              {harvest.notes && (
                                  <p className="text-sm text-gray-600 mt-1">{harvest.notes}</p>
                              )}
                            </div>
                          ))}
                      </div>
                    </div>
                  ));
                })()}
              </div>
            </div>
          )}
        </div>
        {/* Harvest Chart */}
        {chartData.length > 0 && (
            <div className="bg-gray-50 p-6 rounded-lg">
              <h4 className="text-lg font-semibold text-gray-900 mb-4">Диаграмма урожая</h4>
              <div className="space-y-4">
                <div className="flex items-center justify-between text-sm text-gray-600">
                  <span>Размер урожая ({chartData[0]?.unit})</span>
                  <span>Максимально: {maxQuantity.toFixed(1)} {chartData[0]?.unit}</span>
                </div>

                <div className="relative">
                  {/* Y-axis labels */}
                  <div className="absolute left-0 top-0 bottom-0 w-12 flex flex-col justify-between text-xs text-gray-500">
                    <span>{maxQuantity.toFixed(1)}</span>
                    <span>{(maxQuantity * 0.75).toFixed(1)}</span>
                    <span>{(maxQuantity * 0.5).toFixed(1)}</span>
                    <span>{(maxQuantity * 0.25).toFixed(1)}</span>
                    <span>0</span>
                  </div>

                  {/* Chart area */}
                  <div className="ml-14 border-l border-b border-gray-300">
                    <div className="flex items-end space-x-1 p-4 min-h-[200px]">
                      {chartData.map((data, index) => {
                        const height = maxQuantity > 0 ? (data.quantity / maxQuantity) * 160 : 0;
                        return (
                            <div key={index} className="flex flex-col items-center group relative">
                              {/* Bar */}
                              <div
                                  className="bg-green-500 hover:bg-green-600 transition-colors rounded-t min-w-[20px] cursor-pointer"
                                  style={{
                                    height: `${height}px`,
                                    width: `${Math.max(20, 300 / chartData.length)}px`
                                  }}
                              />

                              {/* Tooltip */}
                              <div className="absolute bottom-full mb-2 hidden group-hover:block bg-gray-800 text-white text-xs rounded px-2 py-1 whitespace-nowrap z-10">
                                <div>{new Date(data.date).toLocaleDateString()}</div>
                                <div>{data.quantity.toFixed(1)} {data.unit}</div>
                                <div className="absolute top-full left-1/2 transform -translate-x-1/2 border-4 border-transparent border-t-gray-800"></div>
                              </div>

                              {/* X-axis label */}
                              <div className="text-xs text-gray-500 mt-2 transform -rotate-45 origin-top-left whitespace-nowrap">
                                {new Date(data.date).toLocaleDateString('en-US', {
                                  month: 'short',
                                  day: 'numeric'
                                })}
                              </div>
                            </div>
                        );
                      })}
                    </div>
                  </div>

                  {/* X-axis title */}
                  <div className="text-center text-sm text-gray-600 mt-4">
                    Даты сбора урожая
                  </div>
                </div>
              </div>
            </div>
        )}
      </div>
    </div>
  );
};

export default PlantStatisticsComponent;