import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, User, Mail, Phone, Smartphone, Building2, FileText, Pencil, Trash2 } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { DashboardNav } from '@/components/dashboard/DashboardNav';
import { supabase } from '@/integrations/supabase/client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useToast } from '@/hooks/use-toast';
import { StatusBadge } from '@/components/dashboard/StatusBadge';
import { EmptyState } from '@/components/dashboard/EmptyState';
import { normalizeStatus } from '@/lib/leadStatus';
import { fmtListDate } from '@/lib/dateFormat';
import { EditContactModal } from '@/components/dashboard/EditContactModal';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import sutekiLogo from '@/assets/suteki-logo.png';

interface Contact {
  id: string;
  first_name: string | null;
  last_name: string | null;
  name: string | null;
  email: string;
  phone: string | null;
  direct_phone: string | null;
  mobile_phone: string | null;
  title: string | null;
  role: string | null;
  company_id: string | null;
}

interface CompanyOpt { id: string; name: string }
interface Lead {
  id: string;
  status: string;
  project_description: string | null;
  next_followup_date: string | null;
  updated_at: string;
}

export default function ContactDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user, loading: authLoading, isSalesTeam } = useAuth();
  const { toast } = useToast();

  const [contact, setContact] = useState<Contact | null>(null);
  const [company, setCompany] = useState<CompanyOpt | null>(null);
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAll, setShowAll] = useState(false);
  const [showEdit, setShowEdit] = useState(false);
  const [showDelete, setShowDelete] = useState(false);
  const [deleting, setDeleting] = useState(false);

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

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

  const load = async () => {
    setLoading(true);
    const { data: c, error } = await supabase
      .from('contacts')
      .select('id, first_name, last_name, name, email, phone, direct_phone, mobile_phone, title, role, company_id')
      .eq('id', id!)
      .maybeSingle();
    if (error || !c) {
      toast({ title: 'Fel', description: 'Kunde inte hämta kontakt', variant: 'destructive' });
      navigate('/dashboard/sales');
      return;
    }
    setContact(c as Contact);
    if (c.company_id) {
      const { data: comp } = await supabase
        .from('companies').select('id, name').eq('id', c.company_id).maybeSingle();
      if (comp) setCompany(comp as CompanyOpt);
    }
    const { data: ls } = await supabase
      .from('leads')
      .select('id, status, project_description, next_followup_date, updated_at')
      .eq('contact_id', id!)
      .order('updated_at', { ascending: false });
    setLeads((ls || []) as Lead[]);
    setLoading(false);
  };

  if (authLoading || loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-6 py-8 max-w-3xl">
          <Skeleton className="h-8 w-48 mb-6" />
          <Skeleton className="h-64" />
        </div>
      </div>
    );
  }

  if (!contact) return null;
  const displayName = [contact.first_name, contact.last_name].filter(Boolean).join(' ') || contact.name || contact.email;
  const visible = showAll ? leads : leads.slice(0, 3);

  const handleDelete = async () => {
    setDeleting(true);
    const { error } = await supabase.from('contacts').delete().eq('id', contact.id);
    setDeleting(false);
    if (error) {
      toast({ title: 'Kunde inte radera', description: error.message, variant: 'destructive' });
      return;
    }
    toast({ title: '🗑️ Kontakt raderad' });
    if (contact.company_id) navigate(`/dashboard/companies/${contact.company_id}`);
    else navigate('/dashboard/sales');
  };

  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(-1)}>
            <ArrowLeft className="h-4 w-4 mr-2" /> Tillbaka
          </Button>
        </div>
      </header>

      <main className="container mx-auto px-4 md:px-6 py-8 max-w-3xl space-y-6">
        <Card>
          <CardHeader className="pb-3">
             <div className="flex flex-wrap items-center justify-between gap-2">
              <CardTitle className="flex items-center gap-2 text-sm font-semibold tracking-tight text-muted-foreground">
                <User className="h-4 w-4" /> Kontakt
              </CardTitle>
              <div className="flex items-center gap-2">
                <Button size="sm" variant="outline" onClick={() => setShowEdit(true)}>
                  <Pencil className="h-4 w-4 mr-1" /> Redigera
                </Button>
                <Button size="sm" variant="outline" className="text-destructive hover:text-destructive hover:bg-destructive/10" onClick={() => setShowDelete(true)}>
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-3">
            <div>
               <h1 className="text-2xl font-bold text-foreground break-words">{displayName}</h1>
              {(contact.title || contact.role) && (
                <p className="text-sm text-muted-foreground mt-0.5">{contact.title || contact.role}</p>
              )}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 pt-2">
              <a href={`mailto:${contact.email}`} className="flex items-center gap-2 text-sm text-accent hover:underline">
                <Mail className="h-4 w-4 text-muted-foreground" /> {contact.email}
              </a>
              {contact.direct_phone && (
                <a href={`tel:${contact.direct_phone}`} className="flex items-center gap-2 text-sm hover:underline">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  <span>{contact.direct_phone}</span>
                  <span className="text-xs text-muted-foreground">· direkt</span>
                </a>
              )}
              {contact.mobile_phone && (
                <a href={`tel:${contact.mobile_phone}`} className="flex items-center gap-2 text-sm hover:underline">
                  <Smartphone className="h-4 w-4 text-muted-foreground" />
                  <span>{contact.mobile_phone}</span>
                  <span className="text-xs text-muted-foreground">· mobil</span>
                </a>
              )}
              {!contact.direct_phone && !contact.mobile_phone && contact.phone && (
                <a href={`tel:${contact.phone}`} className="flex items-center gap-2 text-sm hover:underline">
                  <Phone className="h-4 w-4 text-muted-foreground" /> {contact.phone}
                </a>
              )}
              {company && (
                <Link to={`/dashboard/companies/${company.id}`} className="flex items-center gap-2 text-sm text-accent hover:underline md:col-span-2">
                  <Building2 className="h-4 w-4 text-muted-foreground" /> {company.name}
                </Link>
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-sm font-semibold tracking-tight text-muted-foreground">
              <FileText className="h-4 w-4" /> Förfrågningar ({leads.length})
            </CardTitle>
          </CardHeader>
          <CardContent>
            {leads.length === 0 ? (
              <EmptyState icon={FileText} title="Inga förfrågningar för denna kontakt" />
            ) : (
              <div className="divide-y divide-border -mx-2">
                {visible.map((l) => (
                  <Link
                    key={l.id}
                    to={`/dashboard/leads/${l.id}`}
                    className="block px-3 py-3 hover:bg-secondary/40 transition-colors rounded-sm"
                  >
                    <div className="flex items-center justify-between gap-3">
                      <div className="min-w-0 flex-1">
                        <div className="font-semibold text-base text-foreground truncate">
                          {l.project_description?.trim() || '(Ingen rubrik)'}
                        </div>
                        {l.next_followup_date && (
                          <div className="text-xs text-muted-foreground/70 mt-1">
                            {fmtListDate(l.next_followup_date)}
                          </div>
                        )}
                      </div>
                      <StatusBadge status={normalizeStatus(l.status)} className="shrink-0 text-[10px]" />
                    </div>
                  </Link>
                ))}
                {leads.length > 3 && (
                  <button
                    type="button"
                    onClick={() => setShowAll((v) => !v)}
                    className="w-full text-left px-3 pt-3 text-xs text-muted-foreground hover:text-accent transition-colors"
                  >
                    {showAll ? 'Visa färre' : `Visa alla förfrågningar (${leads.length}) →`}
                  </button>
                )}
              </div>
            )}
          </CardContent>
        </Card>

        <EditContactModal
          open={showEdit}
          onOpenChange={setShowEdit}
          contact={contact}
          onSaved={load}
        />
        <AlertDialog open={showDelete} onOpenChange={setShowDelete}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Radera {displayName}?</AlertDialogTitle>
              <AlertDialogDescription>
                Kontakten tas bort permanent. Förfrågningar kopplade till kontakten blir kvar men förlorar kopplingen. Åtgärden kan inte ångras.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>Avbryt</AlertDialogCancel>
              <AlertDialogAction onClick={handleDelete} disabled={deleting} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                {deleting ? 'Raderar...' : 'Radera'}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </main>
    </div>
  );
}
