import { useEffect, useState } from 'react';
import { Plus, FileText, Loader2, ExternalLink, Trash2 } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { EmptyState } from '@/components/dashboard/EmptyState';
import { fmtListDate } from '@/lib/dateFormat';

interface Quote {
  id: string;
  amount: number | null;
  service: string | null;
  file_url: string | null;
  notes: string | null;
  created_at: string;
}

interface QuoteSectionProps {
  leadId: string;
  companyId: string | null;
  contactId: string | null;
  onQuoteCreated?: () => void;
}

export function QuoteSection({ leadId, companyId, contactId, onQuoteCreated }: QuoteSectionProps) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [amount, setAmount] = useState('');
  const [service, setService] = useState('');
  const [fileUrl, setFileUrl] = useState('');
  const [notes, setNotes] = useState('');

  const fetchQuotes = async () => {
    const { data } = await supabase
      .from('quotes')
      .select('*')
      .eq('lead_id', leadId)
      .order('created_at', { ascending: false });
    setQuotes((data || []) as Quote[]);
  };

  useEffect(() => {
    fetchQuotes();
  }, [leadId]);

  const handleCreate = async () => {
    if (!service.trim() && !amount) {
      toast({ title: 'Fyll i tjänst eller belopp', variant: 'destructive' });
      return;
    }
    setSaving(true);
    const { error } = await supabase.from('quotes').insert({
      lead_id: leadId,
      company_id: companyId,
      contact_id: contactId,
      amount: amount ? Number(amount) : 0,
      service: service.trim() || null,
      file_url: fileUrl.trim() || null,
      notes: notes.trim() || null,
      created_by: user?.id,
    });
    setSaving(false);
    if (error) {
      toast({ title: 'Fel', description: error.message, variant: 'destructive' });
      return;
    }
    // Sync offertvärde till lead så det syns direkt i pipeline
    if (amount) {
      await supabase.from('leads').update({ amount: Number(amount) }).eq('id', leadId);
    }
    toast({ title: '✅ Offert skapad', description: 'Status uppdaterad till Proposal sent' });
    setAmount(''); setService(''); setFileUrl(''); setNotes('');
    setOpen(false);
    fetchQuotes();
    onQuoteCreated?.();
  };

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from('quotes').delete().eq('id', id);
    if (error) {
      toast({ title: 'Fel', description: error.message, variant: 'destructive' });
      return;
    }
    fetchQuotes();
  };

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

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-3">
        <CardTitle className="flex items-center gap-2 text-sm font-semibold tracking-tight text-muted-foreground">
          <FileText className="h-4 w-4" />
          Offerter
        </CardTitle>
        <Button size="sm" onClick={() => setOpen(true)}>
          <Plus className="h-4 w-4 mr-1" /> Ny offert
        </Button>
      </CardHeader>
      <CardContent>
        {quotes.length === 0 ? (
          <EmptyState icon={FileText} title="Inga offerter skapade" />
        ) : (
          <div className="divide-y divide-border -mx-1">
            {quotes.map((q) => (
              <div key={q.id} className="flex items-center justify-between px-3 py-2.5">
                <div className="flex-1 min-w-0">
                  <div className="flex items-baseline gap-2 text-sm">
                    <span className="font-semibold text-foreground">{formatCurrency(q.amount)}</span>
                    <span className="text-muted-foreground truncate">{q.service || 'Offert'}</span>
                  </div>
                  <p className="text-[11px] text-muted-foreground/70 mt-0.5 font-mono">
                    {fmtListDate(q.created_at)}
                  </p>
                  {q.notes && <p className="text-xs text-muted-foreground mt-1">{q.notes}</p>}
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  {q.file_url && (
                    <a href={q.file_url} target="_blank" rel="noopener noreferrer">
                      <Button size="icon" variant="ghost" className="h-8 w-8">
                        <ExternalLink className="h-4 w-4" />
                      </Button>
                    </a>
                  )}
                  <Button size="icon" variant="ghost" className="h-8 w-8" onClick={() => handleDelete(q.id)}>
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="bg-card border-border">
          <DialogHeader>
            <DialogTitle>Ny offert</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Tjänst / Produkt</Label>
              <Input value={service} onChange={(e) => setService(e.target.value)} placeholder="t.ex. Hologrambox 75 tum, 1 vecka" />
            </div>
            <div className="space-y-2">
              <Label>Offertvärde (SEK)</Label>
              <Input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="50000" />
            </div>
            <div className="space-y-2">
              <Label>Länk till PDF/fil (valfritt)</Label>
              <Input value={fileUrl} onChange={(e) => setFileUrl(e.target.value)} placeholder="https://..." />
            </div>
            <div className="space-y-2">
              <Label>Anteckning (valfritt)</Label>
              <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Avbryt</Button>
            <Button onClick={handleCreate} disabled={saving}>
              {saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Plus className="h-4 w-4 mr-2" />}
              Spara offert
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
