
import React, { useState } from 'react';
import { FinesCard } from './FinesCard';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { RefreshCcw } from 'lucide-react';

const FinesCardDebug = (initialProps) => {

  const sampleData = [
    { name: 'Excesso de Velocidade', value: 450.00, color: '#ef4444' }, // Red
    { name: 'Estacionamento Irregular', value: 250.00, color: '#f59e0b' }, // Amber
    { name: 'Documentação', value: 150.00, color: '#3b82f6' }, // Blue
  ];

  const totalSampleValue = sampleData.reduce((acc, curr) => acc + curr.value, 0);

  // Helper to generate consistent data
  const generateChartData = (period, current, previous) => {
      if (period === '30d') {
          return [
              { name: 'Sem 1', value: previous * 0.8 },
              { name: 'Sem 2', value: previous * 1.1 },
              { name: 'Sem 3', value: previous * 0.9 },
              { name: 'Atual', value: current, active: true } // Highlighted
          ];
      }

      if (period === '60d') {
         return [
             { name: 'Mês -1', value: previous * 0.9 },
             { name: 'Anterior', value: previous },
             { name: 'Atual', value: current, active: true }
         ];
      }

      if (period === '120d') {
         return [
             { name: 'Mês -3', value: previous * 1.2 },
             { name: 'Mês -2', value: previous * 0.8 },
             { name: 'Anterior', value: previous },
             { name: 'Atual', value: current, active: true }
         ];
      }
      return [];
  };

  const [state, setState] = useState(() => {
     const initialCurrent = 850;
     const initialPrev = 1100;
     return {
        currentValue: initialCurrent,
        currentCount: 3,
        previousValue: initialPrev,
        previousCount: 6,
        hasData: true,
        isLoading: false,
        period: '30d',
        data: sampleData,
        monthlyData: generateChartData('30d', initialCurrent, initialPrev),
        ...initialProps
     };
  });

  const toggleData = () => {
    setState(prev => ({
      ...prev,
      hasData: !prev.hasData,
      currentValue: !prev.hasData ? totalSampleValue : 0,
      currentCount: !prev.hasData ? 3 : 0
    }));
  };

  const handlePeriodChange = (p) => {
    console.log('Period Changed:', p);
    
    // Simulate API logic: distinct values for each period
    let newCurrent, newPrev, newCount;
    
    if (p === '30d') { newCurrent = 850; newPrev = 1100; newCount = 3; }
    else if (p === '60d')  { newCurrent = 1450; newPrev = 1200; newCount = 5; }
    else if (p === '120d') { newCurrent = 2100; newPrev = 1800; newCount = 8; }
    else { newCurrent = 0; newPrev = 0; newCount = 0; }

    setState(prev => ({ 
        ...prev, 
        period: p, // Update the period in state
        currentValue: newCurrent,
        previousValue: newPrev,
        currentCount: newCount,
        monthlyData: generateChartData(p, newCurrent, newPrev)
    }));
  };

  const updatePrevValue = (e) => {
    const val = Number(e.target.value);
    setState(prev => ({
        ...prev,
        previousValue: val,
        monthlyData: generateChartData(prev.period, prev.currentValue, val)
    }));
  };

  return (
    <div className="flex gap-8 items-start w-full">
       {/* Preview Area */}
       <div className="w-[350px] h-[450px] shrink-0">
          <FinesCard 
             currentValue={state.currentValue}
             currentCount={state.currentCount}
             previousValue={state.previousValue}
             previousCount={state.previousCount}
             data={state.hasData ? sampleData : []}
             monthlyData={state.hasData ? state.monthlyData : []}
             isLoading={state.isLoading}
             onPeriodChange={handlePeriodChange}
          />
       </div>

       {/* Controls Area */}
       <div className="flex-1 bg-slate-50 dark:bg-slate-900/50 p-6 rounded-xl border border-slate-200 dark:border-white/10 space-y-6">
          <div className="flex items-center justify-between">
             <h4 className="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-wider">Debug Controls</h4>
             <Button variant="ghost" size="icon" onClick={() => setState(prev => ({ ...prev, isLoading: !prev.isLoading }))} className={state.isLoading ? "text-orange-500" : "text-slate-500 hover:text-slate-900 dark:hover:text-slate-300"}>
                <RefreshCcw className={state.isLoading ? "animate-spin" : ""} size={16} />
             </Button>
          </div>

          <div className="space-y-4">
             <div className="flex items-center justify-between p-3 bg-white dark:bg-white/5 border border-slate-200 dark:border-transparent rounded-lg shadow-sm dark:shadow-none">
                <div className="space-y-1">
                   <Label className="text-slate-700 dark:text-slate-300">Simular Dados</Label>
                   <p className="text-[10px] text-slate-500">Alterna entre estado vazio e populado</p>
                </div>
                <div className="flex items-center">
                   <input 
                      type="checkbox" 
                      checked={state.hasData} 
                      onChange={toggleData}
                      className="w-5 h-5 rounded border-slate-300 dark:border-slate-600 bg-slate-100 dark:bg-slate-700 text-orange-500 focus:ring-orange-500 focus:ring-offset-white dark:focus:ring-offset-slate-900"
                   />
                </div>
             </div>

             <div className="space-y-3 pt-2">
                <div className="flex justify-between text-xs text-slate-500 dark:text-slate-400">
                   <span>Valor Mês Anterior</span>
                   <span className="font-mono text-slate-900 dark:text-white">R$ {state.previousValue}</span>
                </div>
                <input 
                   type="range"
                   min="0"
                   max="5000"
                   step="100"
                   value={state.previousValue}
                   onChange={updatePrevValue}
                   className="w-full h-2 bg-slate-200 dark:bg-slate-700 rounded-lg appearance-none cursor-pointer accent-orange-500"
                />
             </div>
          </div>

          <div className="p-4 rounded-lg bg-slate-100 dark:bg-black/20 border border-slate-200 dark:border-white/5 text-[10px] font-mono text-slate-500 dark:text-slate-400 space-y-2">
             <div><span className="text-purple-600 dark:text-purple-400">Current Value:</span> {state.currentValue}</div>
             <div><span className="text-purple-600 dark:text-purple-400">Reduction:</span> {state.previousValue > 0 ? ((state.currentValue - state.previousValue) / state.previousValue * 100).toFixed(1) : 0}%</div>
          </div>
       </div>
    </div>
  );
};

export default FinesCardDebug;



