import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { format, startOfMonth, endOfMonth, startOfQuarter, endOfQuarter, startOfYear, endOfYear, subMonths, parseISO, isValid } from 'date-fns';
import { sv } from 'date-fns/locale';
import { ArrowLeft, BarChart3, AlertTriangle, CalendarIcon } from 'lucide-react';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid } from 'recharts';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { DashboardNav } from '@/components/dashboard/DashboardNav';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { EmptyState } from '@/components/dashboard/EmptyState';
import sutekiLogo from '@/assets/suteki-logo.png';
import { cn } from '@/lib/utils';

type RangeKey = 'month' | 'quarter' | 'half_year' | 'year' | 'all' | 'custom';

interface WonLead {
  id: string;
  name: string;
  company: string | null;
  amount: number | null;
  close_date: string | null;
  updated_at: string;
}

const RANGE_LABELS: Record<RangeKey, string> = {
  month: 'Denna månad',
  quarter: 'Detta kvartal',
  half_year: 'Senaste halvåret',
  year: 'I år',
  all: 'Sen start',
  custom: 'Valfritt intervall',
};

function computeRange(key: RangeKey, customFrom?: Date, customTo?: Date): { from: Date | null; to: Date | null } {
  const now = new Date();
  switch (key) {
    case 'month': return { from: startOfMonth(now), to: endOfMonth(now) };
    case 'quarter': return { from: startOfQuarter(now), to: endOfQuarter(now) };
    case 'half_year': return { from: startOfMonth(subMonths(now, 5)), to: endOfMonth(now) };
    case 'year': return { from: startOfYear(now), to: endOfYear(now) };
    case 'all': return { from: null, to: null };
    case 'custom': return { from: customFrom || null, to: customTo || null };
  }
}

const fmtSEK = (n: number) =>
  new Intl.NumberFormat('sv-SE', { style: 'currency', currency: 'SEK', maximumFractionDigits: 0 }).format(n);

export default function Statistics() {
  const navigate = useNavigate();
  const { user, loading: authLoading, isSalesTeam } = useAuth();
  const [leads, setLeads] = useState<WonLead[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [range, setRange] = useState<RangeKey>('year');
  const [customFrom, setCustomFrom] = useState<Date | undefined>();
  const [customTo, setCustomTo] = useState<Date | undefined>();

  useEffect(() => {
    if (!authLoading && (!user || !isSalesTeam)) navigate('/auth');
  }, [authLoading, user, isSalesTeam, navigate]);

  useEffect(() => {
    if (user && isSalesTeam) load();
  }, [user, isSalesTeam]);

  const load = async () => {
    setIsLoading(true);
    const { data, error } = await supabase
      .from('leads')
      .select('id, name, company, amount, close_date, updated_at')
      .eq('status', 'won')
      .order('close_date', { ascending: false });
    if (!error) setLeads((data || []) as WonLead[]);
    setIsLoading(false);
  };

  const { from, to } = useMemo(
    () => computeRange(range, customFrom, customTo),
    [range, customFrom, customTo]
  );

  // Split out leads missing win date — never counted in stats
  const leadsWithDate = useMemo(() => leads.filter((l) => !!l.close_date), [leads]);
  const leadsMissingDate = useMemo(() => leads.filter((l) => !l.close_date), [leads]);

  const filtered = useMemo(() => {
    return leadsWithDate.filter((l) => {
      const d = l.close_date ? parseISO(l.close_date) : null;
      if (!d || !isValid(d)) return false;
      if (from && d < from) return false;
      if (to && d > to) return false;
      return true;
    });
  }, [leadsWithDate, from, to]);

  const total = filtered.reduce((sum, l) => sum + (Number(l.amount) || 0), 0);
  const count = filtered.length;
  const avg = count > 0 ? total / count : 0;

  const byMonth = useMemo(() => {
    const map = new Map<string, { key: string; label: string; value: number }>();
    filtered.forEach((l) => {
      const d = parseISO(l.close_date!);
      const key = format(d, 'yyyy-MM');
      const label = format(d, 'MMM yy', { locale: sv });
      const prev = map.get(key)?.value || 0;
      map.set(key, { key, label, value: prev + (Number(l.amount) || 0) });
    });
    return Array.from(map.values()).sort((a, b) => a.key.localeCompare(b.key));
  }, [filtered]);

  return (
    <div className="min-h-screen bg-background">
      <header className="border-b border-border bg-card/50 backdrop-blur-sm sticky top-0 z-40">
         <div className="container mx-auto px-4 md:px-6 py-3 md:py-4 flex items-center justify-between gap-2">
           <div className="flex items-center gap-2 md:gap-6 min-w-0">
             <Link to="/" className="hidden sm:block"><img src={sutekiLogo} alt="Suteki Studios" className="h-6" /></Link>
            <DashboardNav />
          </div>
          <Button variant="ghost" size="sm" onClick={() => navigate('/dashboard/sales')}>
            <ArrowLeft className="h-4 w-4 mr-2" /> Tillbaka
          </Button>
        </div>
      </header>

      <main className="container mx-auto px-4 md:px-6 py-6 md:py-10 max-w-6xl space-y-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-semibold flex items-center gap-2">
              <BarChart3 className="h-6 w-6" /> Statistik – vunna affärer
            </h1>
            <p className="text-sm text-muted-foreground mt-1">
              {RANGE_LABELS[range]}
              {from && to ? ` · ${format(from, 'd MMM yyyy', { locale: sv })} – ${format(to, 'd MMM yyyy', { locale: sv })}` : ''}
            </p>
          </div>

          <div className="flex flex-wrap gap-2 items-center">
            <Select value={range} onValueChange={(v) => setRange(v as RangeKey)}>
              <SelectTrigger className="w-[200px] bg-secondary border-border">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-popover z-50">
                {(Object.keys(RANGE_LABELS) as RangeKey[]).map((k) => (
                  <SelectItem key={k} value={k}>{RANGE_LABELS[k]}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            {range === 'custom' && (
              <>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button variant="outline" size="sm" className={cn('bg-secondary border-border', !customFrom && 'text-muted-foreground')}>
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {customFrom ? format(customFrom, 'yyyy-MM-dd') : 'Från'}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0 bg-popover z-50">
                    <Calendar mode="single" selected={customFrom} onSelect={setCustomFrom} initialFocus className="pointer-events-auto" />
                  </PopoverContent>
                </Popover>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button variant="outline" size="sm" className={cn('bg-secondary border-border', !customTo && 'text-muted-foreground')}>
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {customTo ? format(customTo, 'yyyy-MM-dd') : 'Till'}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0 bg-popover z-50">
                    <Calendar mode="single" selected={customTo} onSelect={setCustomTo} initialFocus className="pointer-events-auto" />
                  </PopoverContent>
                </Popover>
              </>
            )}
          </div>
        </div>

        {/* KPI cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card>
            <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">Totalt värde</CardTitle></CardHeader>
            <CardContent>
              {isLoading ? <Skeleton className="h-8 w-32" /> : <p className="text-2xl font-semibold">{fmtSEK(total)}</p>}
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">Antal vunna affärer</CardTitle></CardHeader>
            <CardContent>
              {isLoading ? <Skeleton className="h-8 w-16" /> : <p className="text-2xl font-semibold">{count}</p>}
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">Genomsnittligt värde</CardTitle></CardHeader>
            <CardContent>
              {isLoading ? <Skeleton className="h-8 w-32" /> : <p className="text-2xl font-semibold">{fmtSEK(avg)}</p>}
            </CardContent>
          </Card>
        </div>

        {/* Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Fördelning per månad</CardTitle>
          </CardHeader>
          <CardContent>
            {byMonth.length === 0 ? (
              <p className="text-sm text-muted-foreground py-8 text-center">Ingen data för vald period.</p>
            ) : (
              <div className="w-full h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={byMonth} margin={{ top: 8, right: 8, left: 8, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                    <XAxis dataKey="label" stroke="hsl(var(--muted-foreground))" fontSize={12} />
                    <YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                    <Tooltip
                      formatter={(v: number) => fmtSEK(v)}
                      contentStyle={{ background: 'hsl(var(--popover))', border: '1px solid hsl(var(--border))', borderRadius: 8 }}
                    />
                    <Bar dataKey="value" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Missing-date warning */}
        {leadsMissingDate.length > 0 && (
          <Card className="border-amber-500/40 bg-amber-500/5">
            <CardContent className="pt-6">
              <div className="flex items-start gap-3">
                <AlertTriangle className="h-5 w-5 text-amber-500 mt-0.5 shrink-0" />
                <div className="flex-1">
                  <p className="text-sm font-medium">
                    {leadsMissingDate.length} vunna affärer saknar vinstdatum och räknas inte med.
                  </p>
                  <ul className="mt-2 space-y-1">
                    {leadsMissingDate.map((l) => (
                      <li key={l.id} className="text-sm">
                        <Link to={`/dashboard/leads/${l.id}`} className="text-accent hover:underline">
                          {l.name} {l.company ? `· ${l.company}` : ''}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Deal list */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Affärer i urvalet</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <Skeleton className="h-32" />
            ) : filtered.length === 0 ? (
              <EmptyState icon={BarChart3} title="Inga vunna affärer för vald period" />
            ) : (
               <div className="overflow-x-auto -mx-6 px-6">
                 <table className="w-full min-w-[560px] text-sm">
                  <thead>
                    <tr className="border-b border-border text-left text-muted-foreground">
                      <th className="py-2 pr-4 font-medium">Vinstdatum</th>
                      <th className="py-2 pr-4 font-medium">Affär</th>
                      <th className="py-2 pr-4 font-medium">Företag</th>
                      <th className="py-2 pr-4 font-medium text-right">Värde</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map((l) => (
                      <tr key={l.id} className="border-b border-border/50 hover:bg-secondary/40">
                        <td className="py-2 pr-4 font-mono text-xs">{l.close_date}</td>
                        <td className="py-2 pr-4">
                          <Link to={`/dashboard/leads/${l.id}`} className="text-accent hover:underline">{l.name}</Link>
                        </td>
                        <td className="py-2 pr-4 text-muted-foreground">{l.company || '—'}</td>
                        <td className="py-2 pr-4 text-right font-medium">{fmtSEK(Number(l.amount) || 0)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}