import React from 'react';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Rectangle,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

interface Payload {
  value?: number;
  name?: string;
  dataKey?: string | number;
}

interface CustomTooltipProps {
  active?: boolean;
  payload?: readonly Payload[];
  label?: string | number;
}

interface BarChartData {
  name: string;
  uv: number;
  isIdeal?: boolean;
  idealRange?: string;
  outsideRange?: string;
}

interface UniformityBarChartProps {
  data: BarChartData[];
}

function CustomTooltip({ payload, label, active }: CustomTooltipProps) {
  if (active && payload && payload.length && label !== undefined) {
    const data = payload[0] as unknown as { payload: BarChartData };
    const chartData = data.payload as BarChartData;
    const labelStr = String(label);

    // If the range has both ideal and outside ranges (like 340-344)
    if (chartData.idealRange && chartData.outsideRange) {
      return (
        <div className='bg-[#18181B] p-2.5 shadow-sm text-white rounded-2xl rounded-bl-none'>
          <p className='m-0 font-bold text-white/50'>Uniformity 2025</p>
          <div className='flex flex-col gap-2 mt-2'>
            <div className='flex items-center justify-between'>
              <div className='flex items-center gap-2'>
                <div className='w-5 h-5 bg-primary rounded-md'></div>
                <span className='text-sm'>Ideal</span>
              </div>
              <span className='text-sm font-medium'>
                {chartData.idealRange}
              </span>
            </div>
            <div className='flex items-center justify-between'>
              <div className='flex items-center gap-2'>
                <div className='w-5 h-5 bg-[#EF4444] rounded-md'></div>
                <span className='text-sm'>Outside</span>
              </div>
              <span className='text-sm font-medium'>
                {chartData.outsideRange}
              </span>
            </div>
            <div className='border-t border-white/20 pt-2 mt-1'>
              <div className='flex items-center justify-between'>
                <span className='text-white/70 text-sm'>Total Birds:</span>
                <span className='font-semibold'>{payload[0].value}</span>
              </div>
            </div>
            <div className='text-center text-xs text-white/50'>{labelStr}</div>
          </div>
        </div>
      );
    }

    // If the range has only ideal range
    if (chartData.idealRange) {
      return (
        <div className='bg-[#18181B] p-2.5 shadow-sm text-white rounded-2xl rounded-bl-none'>
          <p className='m-0 font-bold text-white/50'>Uniformity 2025</p>
          <div className='flex items-center gap-2 mt-2 justify-between'>
            <div className='flex items-center gap-2'>
              <div className='w-5 h-5 bg-primary rounded-md'></div>
              <span className='text-sm'>Ideal</span>
            </div>
            <span className='text-sm font-medium'>{chartData.idealRange}</span>
          </div>
          <div className='border-t border-white/20 pt-2 mt-2'>
            <div className='flex items-center justify-between'>
              <span className='text-white/70 text-sm'>Birds:</span>
              <span className='font-semibold'>{payload[0].value}</span>
            </div>
          </div>
          <div className='text-center text-xs text-white/50 mt-1'>
            {labelStr}
          </div>
        </div>
      );
    }

    // If the range has only outside range
    if (chartData.outsideRange) {
      return (
        <div className='bg-[#18181B] p-2.5 shadow-sm text-white rounded-2xl rounded-bl-none'>
          <p className='m-0 font-bold text-white/50'>Uniformity 2025</p>
          <div className='flex items-center gap-2 mt-2 justify-between'>
            <div className='flex items-center gap-2'>
              <div className='w-5 h-5 bg-[#EF4444] rounded-md'></div>
              <span className='text-sm'>Outside</span>
            </div>
            <span className='text-sm font-medium'>
              {chartData.outsideRange}
            </span>
          </div>
          <div className='border-t border-white/20 pt-2 mt-2'>
            <div className='flex items-center justify-between'>
              <span className='text-white/70 text-sm'>Birds:</span>
              <span className='font-semibold'>{payload[0].value}</span>
            </div>
          </div>
          <div className='text-center text-xs text-white/50 mt-1'>
            {labelStr}
          </div>
        </div>
      );
    }

    // Fallback for backward compatibility
    return (
      <div className='bg-[#18181B] p-2.5 shadow-sm text-white rounded-2xl rounded-bl-none'>
        <p className='m-0 font-bold text-white/50'>Uniformity 2025</p>
        <div className='flex items-center gap-2 mt-2 justify-between'>
          <div className='flex items-center gap-2'>
            <div
              className='w-5 h-5 rounded-md'
              style={{
                backgroundColor: chartData.isIdeal ? '#0069E0' : '#EF4444',
              }}
            ></div>
            <span className='text-sm'>
              {chartData.isIdeal ? 'Ideal' : 'Outside'}
            </span>
          </div>
          <span className='text-sm font-medium'>{labelStr}</span>
        </div>
        <div className='border-t border-white/20 pt-2 mt-2'>
          <div className='flex items-center justify-between'>
            <span className='text-white/70 text-sm'>Birds:</span>
            <span className='font-semibold'>{payload[0].value}</span>
          </div>
        </div>
      </div>
    );
  }

  return null;
}

const UniformityBarChart: React.FC<UniformityBarChartProps> = ({ data }) => {
  const margin = {
    top: 20,
    right: 30,
    left: 0,
    bottom: 5,
  };

  return (
    <ResponsiveContainer
      width='100%'
      height='100%'
      className='min-h-[270px] xl:min-h-72'
    >
      <BarChart data={data} margin={margin} barGap={20}>
        <defs>
          <linearGradient id='activeBarGradient' x1='0' y1='0' x2='0' y2='1'>
            <stop offset='0%' stopColor='#0069E0' stopOpacity={0.01} />
            <stop offset='40%' stopColor='#0069E0' stopOpacity={1} />
            <stop offset='100%' stopColor='#0069E0' stopOpacity={1} />
          </linearGradient>
        </defs>
        <XAxis
          dataKey='name'
          axisLine={false}
          tickLine={false}
          label={{
            value: 'Body Weight Range',
            position: 'insideBottom',
            offset: -5,
            style: { textAnchor: 'middle', fontSize: 14, fill: '#18181B33' },
          }}
        />
        <YAxis
          axisLine={false}
          tickLine={false}
          label={{
            value: 'Number of Birds',
            angle: -90,
            position: 'insideLeft',
            style: { textAnchor: 'middle', fontSize: 14, fill: '#18181B33' },
          }}
        />
        <Tooltip
          cursor={false}
          content={CustomTooltip}
          wrapperStyle={{
            width: '200px',
          }}
        />
        <CartesianGrid vertical={false} />
        <Bar
          name='Birds'
          dataKey='uv'
          radius={[25, 25, 0, 0]}
          activeBar={
            <Rectangle
              fill='url(#activeBarGradient)'
              stroke='#18181B'
              strokeWidth={0}
              radius={[25, 25, 0, 0]}
            />
          }
        >
          {data.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={entry.isIdeal ? 'url(#activeBarGradient)' : '#FFFFFF'}
              stroke={entry.isIdeal ? '#18181B' : '#DDD'}
              strokeWidth={entry.isIdeal ? 0 : 2}
            />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
};

export default UniformityBarChart;
