import { useEffect, useState, useMemo } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { isToday, isBefore, isAfter, startOfDay } from 'date-fns';
import { LogOut, LayoutDashboard, Plus, Kanban, CalendarClock, AlertTriangle, CalendarCheck, Inbox, Building2, Pencil, Trash2 } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { StatusBadge } from '@/components/dashboard/StatusBadge';
import { normalizeStatus } from '@/lib/leadStatus';
import { EmptyState } from '@/components/dashboard/EmptyState';
import { fmtShortDate } from '@/lib/dateFormat';
import { useToast } from '@/hooks/use-toast';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import sutekiLogo from '@/assets/suteki-logo.png';
import { DashboardNav } from '@/components/dashboard/DashboardNav';
import { LeadToCrmButton } from '@/components/dashboard/LeadToCrmButton';

interface FollowupLead {
  id: string;
  name: string | null;
  company: string | null;
  status: string;
  next_followup_date: string | null;
  project_description: string | null;
  email: string | null;
  phone: string | null;
  company_id: string | null;
}

export default function SalesDashboard() {
  const navigate = useNavigate();
  const { user, loading, isSalesTeam, isAdmin, signOut } = useAuth();
  const { toast } = useToast();
  const [leads, setLeads] = useState<FollowupLead[]>([]);
  const [isLoading, setIsLoading] = useState(true);

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

  const fetchLeads = async () => {
    const { data } = await supabase
      .from('leads')
      .select('id, name, company, status, next_followup_date, project_description, email, phone, company_id')
      .not('status', 'in', '(won,lost)')
      .order('next_followup_date', { ascending: true, nullsFirst: false });
    setLeads((data || []) as FollowupLead[]);
    setIsLoading(false);
  };

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

  const handleSignOut = async () => {
    await signOut();
    navigate('/auth');
  };

  const today = startOfDay(new Date());

  const { todayLeads, overdueLeads, upcomingLeads, noDateLeads } = useMemo(() => {
    const tdy: FollowupLead[] = [];
    const overdue: FollowupLead[] = [];
    const upcoming: FollowupLead[] = [];
    const noDate: FollowupLead[] = [];
    leads.forEach((l) => {
      if (!l.next_followup_date) { noDate.push(l); return; }
      const d = startOfDay(new Date(l.next_followup_date));
      if (isToday(d)) tdy.push(l);
      else if (isBefore(d, today)) overdue.push(l);
      else if (isAfter(d, today)) upcoming.push(l);
    });
    return { todayLeads: tdy, overdueLeads: overdue, upcomingLeads: upcoming, noDateLeads: noDate };
  }, [leads, today]);

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from('leads').delete().eq('id', id);
    if (error) {
      toast({ title: 'Kunde inte radera', description: error.message, variant: 'destructive' });
      return;
    }
    setLeads((prev) => prev.filter((l) => l.id !== id));
    toast({ title: '🗑️ Lead raderat' });
  };

  const handleDateChange = async (id: string, value: string) => {
    const next = value || null;
    setLeads((prev) => prev.map((l) => (l.id === id ? { ...l, next_followup_date: next } : l)));
    const { error } = await supabase.from('leads').update({ next_followup_date: next }).eq('id', id);
    if (error) {
      toast({ title: 'Kunde inte spara datum', description: error.message, variant: 'destructive' });
      fetchLeads();
      return;
    }
    toast({ title: next ? '📅 Uppföljningsdatum sparat' : 'Datum borttaget' });
  };

  const renderList = (list: FollowupLead[], emptyMsg: string, withActions = false) => {
    if (list.length === 0) {
      return <EmptyState icon={Inbox} title={emptyMsg} />;
    }
    return (
      <div className="divide-y divide-border">
        {list.map((l) => (
          <div
            key={l.id}
             className="flex flex-wrap sm:flex-nowrap items-center gap-3 px-2 sm:px-3 py-3 hover:bg-secondary/40 transition-colors"
          >
            <input
              type="date"
              value={l.next_followup_date ? l.next_followup_date.slice(0, 10) : ''}
              onChange={(e) => handleDateChange(l.id, e.target.value)}
              aria-label="Uppföljningsdatum"
              title="Sätt uppföljningsdatum"
               className="order-2 sm:order-none shrink-0 h-9 rounded-md border border-input bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"
            />
             <Link to={`/dashboard/leads/${l.id}`} className="order-1 sm:order-none basis-full sm:basis-auto flex-1 min-w-0">
              <div className="font-semibold text-sm text-foreground truncate">
                {l.project_description?.trim() || '(Ingen rubrik)'}
              </div>
              <div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
                <span className="truncate">{l.company || '—'}</span>
                {l.name && (
                  <>
                    <span className="text-muted-foreground">·</span>
                    <span className="truncate">{l.name}</span>
                  </>
                )}
              </div>
            </Link>
             <div className="order-3 sm:order-none flex items-center gap-1 sm:gap-3 ml-auto shrink-0">

              <StatusBadge status={normalizeStatus(l.status)} className="text-[10px]" />
              <LeadToCrmButton
                lead={l}
                onDone={(companyId, contactId) =>
                  setLeads((prev) => prev.map((x) => (x.id === l.id ? { ...x, company_id: companyId } : x)))
                }
              />
              {withActions && (
                <div className="flex items-center gap-1">
                  <Button
                    size="icon"
                    variant="ghost"
                    className="h-7 w-7"
                    onClick={() => navigate(`/dashboard/leads/${l.id}`)}
                    title="Redigera"
                  >
                    <Pencil className="h-3.5 w-3.5" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive hover:text-destructive" title="Radera">
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>Radera lead?</AlertDialogTitle>
                        <AlertDialogDescription>
                          Detta tar bort leadet permanent. Åtgärden kan inte ångras.
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>Avbryt</AlertDialogCancel>
                        <AlertDialogAction onClick={() => handleDelete(l.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                          Radera
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };

  if (loading || isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="animate-pulse text-muted-foreground">Laddar...</div>
      </div>
    );
  }

  if (!isSalesTeam) return null;

  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>
           <div className="flex items-center gap-1 sm:gap-3 shrink-0">
            <Button onClick={() => navigate('/dashboard/leads/new')} size="sm">
               <Plus className="h-4 w-4 sm:mr-2" /> <span className="hidden sm:inline">Nytt lead</span><span className="sm:hidden">Nytt</span>
            </Button>
            <span className="text-sm text-muted-foreground hidden md:inline">{user?.email}</span>
             <Button variant="outline" size="sm" onClick={handleSignOut} aria-label="Logga ut" title="Logga ut">
               <LogOut className="h-4 w-4 sm:mr-2" /> <span className="hidden sm:inline">Logga ut</span>
            </Button>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 md:px-6 py-6 md:py-8 max-w-4xl">
        <Tabs defaultValue="today" className="w-full">
           <TabsList className="flex w-full overflow-x-auto justify-start mb-6 h-auto p-1">
             <TabsTrigger value="today" className="flex items-center gap-1.5 shrink-0 px-2 sm:px-3">
               <CalendarClock className="h-4 w-4 hidden sm:block" />
              Idag <span className="ml-1 text-xs opacity-70">({todayLeads.length})</span>
            </TabsTrigger>
             <TabsTrigger value="overdue" className="flex items-center gap-1.5 shrink-0 px-2 sm:px-3">
               <AlertTriangle className="h-4 w-4 hidden sm:block" />
              Försenade <span className="ml-1 text-xs opacity-70">({overdueLeads.length})</span>
            </TabsTrigger>
             <TabsTrigger value="upcoming" className="flex items-center gap-1.5 shrink-0 px-2 sm:px-3">
               <CalendarCheck className="h-4 w-4 hidden sm:block" />
              Kommande <span className="ml-1 text-xs opacity-70">({upcomingLeads.length})</span>
            </TabsTrigger>
             <TabsTrigger value="nodate" className="shrink-0 px-2 sm:px-3">
              Utan datum <span className="ml-1 text-xs opacity-70">({noDateLeads.length})</span>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="today">
            <Card>
              <CardHeader><CardTitle className="text-lg">Att följa upp idag</CardTitle></CardHeader>
              <CardContent>{renderList(todayLeads, 'Inga uppföljningar idag 🎉', true)}</CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="overdue">
            <Card>
              <CardHeader><CardTitle className="text-lg">Försenade uppföljningar</CardTitle></CardHeader>
              <CardContent>{renderList(overdueLeads, 'Inga försenade uppföljningar', true)}</CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="upcoming">
            <Card>
              <CardHeader><CardTitle className="text-lg">Kommande uppföljningar</CardTitle></CardHeader>
              <CardContent>{renderList(upcomingLeads, 'Inga kommande uppföljningar', true)}</CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="nodate">
            <Card>
              <CardHeader><CardTitle className="text-lg">Leads utan uppföljningsdatum</CardTitle></CardHeader>
              <CardContent>{renderList(noDateLeads, 'Alla leads har uppföljningsdatum', true)}</CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </main>
    </div>
  );
}
