import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAuth } from '../context/AuthContext';
import { reports } from '../services/api';
import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';

export default function Reports() {
    const { currentOrg } = useAuth();
    const [days, setDays] = useState(30);
    
    const { data, isLoading } = useQuery({
        queryKey: ['report', currentOrg?.id, days],
        queryFn: () => reports.summary(currentOrg.id, days),
        enabled: !!currentOrg
    });
    
    const handleExport = async () => {
        const res = await reports.exportCsv(currentOrg.id, days);
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const a = document.createElement('a');
        a.href = url;
        a.download = `issues-report-${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
    };
    
    if (!currentOrg) return <div className="p-8 text-center text-gray-400">Select an organization</div>;
    
    const r = data?.data || {};
    
    return (
        <div className="p-8">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold">Reports</h1>
                <div className="flex gap-4">
                    <select value={days} onChange={(e) => setDays(Number(e.target.value))} className="input w-40">
                        <option value={7}>Last 7 days</option>
                        <option value={14}>Last 14 days</option>
                        <option value={30}>Last 30 days</option>
                        <option value={90}>Last 90 days</option>
                    </select>
                    <button onClick={handleExport} className="btn btn-primary">📥 Export CSV</button>
                </div>
            </div>
            
            {/* Summary cards */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div className="card">
                    <p className="text-gray-400 text-sm">Total Issues</p>
                    <p className="text-3xl font-bold mt-1">{r.total_issues || 0}</p>
                </div>
                <div className="card">
                    <p className="text-gray-400 text-sm">Analyzed</p>
                    <p className="text-3xl font-bold mt-1 text-green-400">{r.analyzed_issues || 0}</p>
                </div>
                <div className="card">
                    <p className="text-gray-400 text-sm">PRs Created</p>
                    <p className="text-3xl font-bold mt-1 text-purple-400">{r.prs_created || 0}</p>
                </div>
                <div className="card">
                    <p className="text-gray-400 text-sm">Avg Confidence</p>
                    <p className="text-3xl font-bold mt-1 text-yellow-400">
                        {r.avg_confidence ? `${(r.avg_confidence * 100).toFixed(0)}%` : 'N/A'}
                    </p>
                </div>
            </div>
            
            {/* Chart */}
            <div className="card mb-8">
                <h3 className="font-semibold mb-4">Trend</h3>
                <div className="h-80">
                    {isLoading ? (
                        <div className="flex items-center justify-center h-full text-gray-400">Loading...</div>
                    ) : (
                        <ResponsiveContainer width="100%" height="100%">
                            <AreaChart data={r.daily_breakdown || []}>
                                <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 12 }} />
                                <YAxis tick={{ fill: '#9ca3af', fontSize: 12 }} />
                                <Tooltip contentStyle={{ backgroundColor: '#1f2937', border: '1px solid #374151' }} />
                                <Area type="monotone" dataKey="total" stroke="#6366f1" fill="#6366f1" fillOpacity={0.3} name="Total" />
                                <Area type="monotone" dataKey="analyzed" stroke="#22c55e" fill="#22c55e" fillOpacity={0.3} name="Analyzed" />
                                <Area type="monotone" dataKey="prs_created" stroke="#a855f7" fill="#a855f7" fillOpacity={0.3} name="PRs" />
                            </AreaChart>
                        </ResponsiveContainer>
                    )}
                </div>
            </div>
            
            {/* Top sources */}
            <div className="card">
                <h3 className="font-semibold mb-4">Top Sources</h3>
                <div className="space-y-3">
                    {(r.top_sources || []).map(source => (
                        <div key={source.source} className="flex items-center gap-4">
                            <span className="w-24 text-gray-400">{source.source}</span>
                            <div className="flex-1 bg-gray-700 rounded-full h-4">
                                <div 
                                    className="bg-primary-500 h-4 rounded-full"
                                    style={{ width: `${(source.count / r.total_issues * 100) || 0}%` }}
                                />
                            </div>
                            <span className="w-12 text-right">{source.count}</span>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}
