import { useEffect, useRef, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { LogOut, Kanban, GripVertical, MessageSquarePlus, CalendarIcon, Loader2, Inbox, Building2, Pencil, Check, X, ChevronLeft, ChevronRight } from 'lucide-react';
import { format } from 'date-fns';
import { sv } from 'date-fns/locale';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { STATUS_LABELS, STATUS_COLORS, LeadStatus, PIPELINE_STATUSES, normalizeStatus } from '@/lib/leadStatus';
import { EmptyState } from '@/components/dashboard/EmptyState';
import { fmtShortDate } from '@/lib/dateFormat';
import sutekiLogo from '@/assets/suteki-logo.png';
import { DashboardNav } from '@/components/dashboard/DashboardNav';
import { useIsMobile } from '@/hooks/use-mobile';

interface PipelineLead {
  id: string;
  name: string;
  status: LeadStatus;
  company_id: string | null;
  company_name: string | null;
  amount: number | null;
  next_followup_date: string | null;
}

export default function Pipeline() {
  const isMobile = useIsMobile();
  const navigate = useNavigate();
  const { user, loading, isSalesTeam, isAdmin, signOut } = useAuth();
  const { toast } = useToast();
  const [leads, setLeads] = useState<PipelineLead[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [draggedLead, setDraggedLead] = useState<string | null>(null);
  const [dragOverStage, setDragOverStage] = useState<LeadStatus | null>(null);
  const [noteLeadId, setNoteLeadId] = useState<string | null>(null);
  const [noteText, setNoteText] = useState('');
  const [savingNote, setSavingNote] = useState(false);
  const [editingAmountId, setEditingAmountId] = useState<string | null>(null);
  const [amountDraft, setAmountDraft] = useState<string>('');
  const [savingAmount, setSavingAmount] = useState(false);
  const topScrollRef = useRef<HTMLDivElement | null>(null);
  const bottomScrollRef = useRef<HTMLDivElement | null>(null);
  
  const syncingRef = useRef(false);
  const [scrollWidth, setScrollWidth] = useState(0);

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

  const fetchLeads = async () => {
    const [{ data: leadsData, error: leadsError }, { data: quotesData }] = await Promise.all([
      supabase
        .from('leads')
        .select(`id, name, status, company_id, amount, next_followup_date, companies ( name )`)
        .order('updated_at', { ascending: false }),
      supabase
        .from('quotes')
        .select('lead_id, amount, created_at')
        .order('created_at', { ascending: false }),
    ]);

    if (leadsError) {
      toast({ title: 'Could not fetch leads', description: leadsError.message, variant: 'destructive' });
      setIsLoading(false);
      return;
    }
    const latestQuoteByLead = new Map<string, number>();
    for (const q of quotesData || []) {
      if (!latestQuoteByLead.has((q as any).lead_id)) {
        latestQuoteByLead.set((q as any).lead_id, (q as any).amount);
      }
    }
    const mapped: PipelineLead[] = (leadsData || []).map((l: any) => ({
      id: l.id,
      name: l.name,
      status: normalizeStatus(l.status),
      company_id: l.company_id,
      company_name: l.companies?.name || null,
      amount: l.amount ?? latestQuoteByLead.get(l.id) ?? null,
      next_followup_date: l.next_followup_date,
    }));
    setLeads(mapped);
    setIsLoading(false);
  };

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

  // Realtime: refresh when any lead or quote changes
  useEffect(() => {
    if (!user || !isSalesTeam) return;
    const channel = supabase
      .channel('pipeline-sync')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'leads' }, () => fetchLeads())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'quotes' }, () => fetchLeads())
      .subscribe();
    return () => { supabase.removeChannel(channel); };
  }, [user, isSalesTeam]);

  // Sync horizontal scroll between top proxy bar and main pipeline container
  useEffect(() => {
    const update = () => {
      if (bottomScrollRef.current) setScrollWidth(bottomScrollRef.current.scrollWidth);
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [leads]);

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

  const handleDrop = async (newStage: LeadStatus) => {
    if (!draggedLead) return;
    const lead = leads.find(l => l.id === draggedLead);
    setDraggedLead(null);
    setDragOverStage(null);
    if (!lead || lead.status === newStage) return;

    // Optimistic
    setLeads(prev => prev.map(l => l.id === lead.id ? { ...l, status: newStage } : l));

    const { error } = await supabase
      .from('leads')
      .update({ status: newStage })
      .eq('id', lead.id);

    if (error) {
      toast({ title: 'Could not update status', description: error.message, variant: 'destructive' });
      fetchLeads();
    } else {
      toast({ title: '✏️ Status updated', description: STATUS_LABELS[newStage] });
    }
  };

  const moveLead = async (lead: PipelineLead, newStage: LeadStatus) => {
    if (lead.status === newStage) return;
    setLeads(prev => prev.map(l => l.id === lead.id ? { ...l, status: newStage } : l));
    const { error } = await supabase.from('leads').update({ status: newStage }).eq('id', lead.id);
    if (error) {
      toast({ title: 'Kunde inte uppdatera status', description: error.message, variant: 'destructive' });
      fetchLeads();
    } else toast({ title: 'Status uppdaterad', description: STATUS_LABELS[newStage] });
  };

  const formatCurrency = (v: number | null) => {
    if (v == null || v === 0) return null;
    return new Intl.NumberFormat('sv-SE', { style: 'currency', currency: 'SEK', maximumFractionDigits: 0 }).format(v);
  };

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

  const startEditAmount = (lead: PipelineLead) => {
    setEditingAmountId(lead.id);
    setAmountDraft(lead.amount != null ? String(lead.amount) : '');
  };

  const saveAmount = async (leadId: string) => {
    const trimmed = amountDraft.trim().replace(/\s/g, '').replace(',', '.');
    const parsed = trimmed === '' ? 0 : Number(trimmed);
    if (Number.isNaN(parsed) || parsed < 0) {
      toast({ title: 'Ogiltigt belopp', variant: 'destructive' });
      return;
    }
    setSavingAmount(true);
    setLeads((prev) => prev.map((l) => (l.id === leadId ? { ...l, amount: parsed } : l)));
    const { error } = await supabase.from('leads').update({ amount: parsed }).eq('id', leadId);
    setSavingAmount(false);
    if (error) {
      toast({ title: 'Kunde inte spara', description: error.message, variant: 'destructive' });
      fetchLeads();
      return;
    }
    setEditingAmountId(null);
    setAmountDraft('');
  };

  const handleSaveNote = async () => {
    if (!noteLeadId || !noteText.trim()) return;
    setSavingNote(true);
    const { error } = await supabase.from('lead_notes').insert({
      lead_id: noteLeadId,
      content: noteText.trim(),
      created_by: user?.id,
    });
    setSavingNote(false);
    if (error) {
      toast({ title: 'Kunde inte spara', description: error.message, variant: 'destructive' });
      return;
    }
    toast({ title: '📝 Anteckning sparad' });
    setNoteText('');
    setNoteLeadId(null);
  };

  const handleFollowupChange = async (leadId: string, d: Date | undefined) => {
    const value = d ? format(d, 'yyyy-MM-dd') : null;
    setLeads((prev) => prev.map((l) => (l.id === leadId ? { ...l, next_followup_date: value } : l)));
    const { error } = await supabase.from('leads').update({ next_followup_date: value }).eq('id', leadId);
    if (error) {
      toast({ title: 'Kunde inte uppdatera datum', variant: 'destructive' });
      fetchLeads();
    }
  };

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

  const getLeadsByStage = (s: LeadStatus) => leads.filter(l => l.status === s);
  const getStageTotal = (s: LeadStatus) =>
    getLeadsByStage(s).reduce((sum, l) => sum + (l.amount || 0), 0);

  const syncScroll = (source: HTMLDivElement | null) => {
    if (!source || syncingRef.current) return;
    syncingRef.current = true;
    [topScrollRef.current, bottomScrollRef.current].forEach((el) => {
      if (el && el !== source) el.scrollLeft = source.scrollLeft;
    });
    requestAnimationFrame(() => { syncingRef.current = false; });
  };

  const scrollByAmount = (delta: number) => {
    bottomScrollRef.current?.scrollBy({ left: delta, behavior: 'smooth' });
  };



  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-4">
             <span className="text-sm text-muted-foreground hidden lg:inline">{user?.email}</span>
             <Button variant="outline" size="sm" onClick={handleSignOut} aria-label="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 space-y-6">
         <div className="flex flex-wrap items-center justify-between gap-2">
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-3"><Kanban className="h-6 w-6 text-accent" />Pipeline</h1>
           <p className="text-sm text-muted-foreground hidden md:block">Dra och släpp · Klicka för att öppna</p>
        </div>

        <div className="hidden md:flex items-center gap-2">
          <button
            type="button"
            aria-label="Skrolla vänster"
            onClick={() => scrollByAmount(-560)}
            className="flex-shrink-0 h-8 w-8 rounded-md border border-border bg-card hover:bg-accent/10 hover:border-accent text-muted-foreground hover:text-accent flex items-center justify-center transition"
          >
            <ChevronLeft className="h-4 w-4" />
          </button>
          <div
            ref={topScrollRef}
            onScroll={(e) => syncScroll(e.currentTarget)}
            className="flex-1 overflow-x-auto pipeline-scroll"
          >
            <div style={{ width: scrollWidth, height: 1 }} />
          </div>
          <button
            type="button"
            aria-label="Skrolla höger"
            onClick={() => scrollByAmount(560)}
            className="flex-shrink-0 h-8 w-8 rounded-md border border-border bg-card hover:bg-accent/10 hover:border-accent text-muted-foreground hover:text-accent flex items-center justify-center transition"
          >
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>

        <div
          ref={bottomScrollRef}
          onScroll={(e) => syncScroll(e.currentTarget)}
          className="flex flex-col md:flex-row gap-4 md:overflow-x-auto pb-2 pipeline-scroll-hidden"
        >
          {PIPELINE_STATUSES.map(stage => {
            const colors = STATUS_COLORS[stage];
            const stageLeads = getLeadsByStage(stage);
            const stageTotal = getStageTotal(stage);
            return (
              <div
                key={stage}
                className={`w-full md:min-w-[260px] md:w-auto flex-shrink-0 rounded-xl border ${colors.border} bg-card/50 p-3 md:p-4 transition-all ${
                  draggedLead && dragOverStage === stage ? 'ring-2 ring-accent/50 bg-accent/5' : ''
                }`}
                onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; if (dragOverStage !== stage) setDragOverStage(stage); }}
                onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragOverStage(null); }}
                onDrop={() => handleDrop(stage)}
              >
                <div className={`text-center mb-2 text-sm font-bold ${colors.text}`}>
                  {stageTotal > 0 ? formatTotal(stageTotal) : <span className="text-muted-foreground/60 font-normal text-xs">— inget värde —</span>}
                </div>
                <div className={`flex items-center justify-between mb-4 pb-3 border-b ${colors.border}`}>
                  <h3 className={`font-semibold text-xs uppercase tracking-wider ${colors.text}`}>{STATUS_LABELS[stage]}</h3>
                  <span className={`text-[11px] font-semibold px-2 py-0.5 rounded-full ${colors.bg} ${colors.text}`}>{stageLeads.length}</span>
                </div>
                 <div className="space-y-2 md:min-h-[400px]">
                  {stageLeads.length === 0 && (
                    <EmptyState icon={Inbox} title="Inga leads" className="py-6" />
                  )}
                  {stageLeads.map(lead => (
                    <div
                      key={lead.id}
                       draggable={!isMobile}
                      onDragStart={(e) => { e.dataTransfer.effectAllowed = 'move'; setDraggedLead(lead.id); }}
                      onDragEnd={() => { setDraggedLead(null); setDragOverStage(null); }}
                      className={`group p-2.5 rounded-md bg-secondary border border-border cursor-grab active:cursor-grabbing hover:border-accent hover:shadow-md hover:-translate-y-0.5 transition-all select-none ${
                        draggedLead === lead.id ? 'opacity-50 scale-95' : ''
                      }`}
                    >
                      <div
                        className="flex items-start gap-1.5"
                        onClick={() => { if (!draggedLead) navigate(`/dashboard/leads/${lead.id}`); }}
                      >
                        <GripVertical className="h-3.5 w-3.5 text-muted-foreground/60 flex-shrink-0 mt-0.5" />
                        <div className="flex-1 min-w-0">
                          <div className="font-semibold text-foreground text-sm break-words leading-tight">
                            {lead.company_name || 'Inget företag'}
                          </div>
                          <p className="text-[11px] text-muted-foreground mt-0.5 break-words">{lead.name}</p>
                          <div
                            className="mt-1.5"
                            onClick={(e) => e.stopPropagation()}
                            onMouseDown={(e) => e.stopPropagation()}
                          >
                            {editingAmountId === lead.id ? (
                              <div className="flex items-center gap-1" draggable={false} onDragStart={(e) => e.preventDefault()}>
                                <Input
                                  type="text"
                                  inputMode="decimal"
                                  autoFocus
                                  value={amountDraft}
                                  onChange={(e) => setAmountDraft(e.target.value)}
                                  onKeyDown={(e) => {
                                    if (e.key === 'Enter') { e.preventDefault(); saveAmount(lead.id); }
                                    if (e.key === 'Escape') { setEditingAmountId(null); setAmountDraft(''); }
                                  }}
                                  placeholder="0"
                                  className="h-6 text-xs px-1.5"
                                />
                                <button
                                  type="button"
                                  className="p-1 text-accent hover:bg-accent/10 rounded"
                                  onClick={() => saveAmount(lead.id)}
                                  disabled={savingAmount}
                                  title="Spara"
                                >
                                  <Check className="h-3 w-3" />
                                </button>
                                <button
                                  type="button"
                                  className="p-1 text-muted-foreground hover:bg-secondary rounded"
                                  onClick={() => { setEditingAmountId(null); setAmountDraft(''); }}
                                  title="Avbryt"
                                >
                                  <X className="h-3 w-3" />
                                </button>
                              </div>
                            ) : (
                              <button
                                type="button"
                                draggable={false}
                                onDragStart={(e) => e.preventDefault()}
                                onClick={() => startEditAmount(lead)}
                                className="text-xs font-bold text-accent hover:underline flex items-center gap-1"
                                title="Redigera offertvärde"
                              >
                                {formatCurrency(lead.amount) || (
                                  <span className="text-muted-foreground/70 font-normal">+ Lägg till offertvärde</span>
                                )}
                                <Pencil className="h-2.5 w-2.5 opacity-60" />
                              </button>
                            )}
                          </div>
                        </div>
                      </div>
                       <div className="md:hidden mt-3" onClick={(e) => e.stopPropagation()}>
                         <Select value={lead.status} onValueChange={(value) => moveLead(lead, value as LeadStatus)}>
                           <SelectTrigger aria-label={`Ändra status för ${lead.company_name || lead.name}`} className="h-9 bg-card"><SelectValue /></SelectTrigger>
                           <SelectContent>{PIPELINE_STATUSES.map((s) => <SelectItem key={s} value={s}>{STATUS_LABELS[s]}</SelectItem>)}</SelectContent>
                         </Select>
                       </div>
                      <div
                        className="flex items-center justify-between mt-2 pt-2 border-t border-border/50"
                        onClick={(e) => e.stopPropagation()}
                        onMouseDown={(e) => e.stopPropagation()}
                      >
                        <Popover>
                          <PopoverTrigger asChild>
                            <button
                              type="button"
                              draggable={false}
                              onDragStart={(e) => e.preventDefault()}
                              className="text-[11px] text-muted-foreground/80 hover:text-accent transition-colors flex items-center gap-1"
                            >
                              <CalendarIcon className="h-3 w-3" />
                              {lead.next_followup_date ? fmtShortDate(lead.next_followup_date) : 'Sätt datum'}
                            </button>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0 z-50 bg-popover" align="start">
                            <Calendar
                              mode="single"
                              selected={lead.next_followup_date ? new Date(lead.next_followup_date) : undefined}
                              onSelect={(d) => handleFollowupChange(lead.id, d)}
                              initialFocus
                              className="pointer-events-auto"
                            />
                            {lead.next_followup_date && (
                              <div className="p-2 border-t border-border">
                                <Button size="sm" variant="ghost" className="w-full text-xs"
                                  onClick={() => handleFollowupChange(lead.id, undefined)}>
                                  Rensa datum
                                </Button>
                              </div>
                            )}
                          </PopoverContent>
                        </Popover>
                        <Popover open={noteLeadId === lead.id} onOpenChange={(o) => { setNoteLeadId(o ? lead.id : null); if (!o) setNoteText(''); }}>
                          <PopoverTrigger asChild>
                            <button
                              type="button"
                              draggable={false}
                              onDragStart={(e) => e.preventDefault()}
                               className="md:opacity-0 md:group-hover:opacity-100 p-2 text-muted-foreground hover:text-accent transition"
                              title="Snabbanteckning"
                            >
                              <MessageSquarePlus className="h-3.5 w-3.5" />
                            </button>
                          </PopoverTrigger>
                          <PopoverContent className="w-72 z-50 bg-popover p-3 space-y-2" align="end">
                            <p className="text-xs font-semibold text-muted-foreground">Ny anteckning</p>
                            <Textarea
                              value={noteText}
                              onChange={(e) => setNoteText(e.target.value)}
                              rows={3}
                              placeholder="Skriv en snabb anteckning..."
                              autoFocus
                            />
                            <div className="flex justify-end gap-2">
                              <Button size="sm" variant="ghost" onClick={() => { setNoteLeadId(null); setNoteText(''); }}>Avbryt</Button>
                              <Button size="sm" onClick={handleSaveNote} disabled={savingNote || !noteText.trim()}>
                                {savingNote ? <Loader2 className="h-3 w-3 animate-spin" /> : 'Spara'}
                              </Button>
                            </div>
                          </PopoverContent>
                        </Popover>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

      </main>
    </div>
  );
}
