import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { 
  ArrowLeft, Building2, User, Mail, Phone, Globe,
  FileText, ExternalLink, MapPin, UserPlus, Smartphone, Pencil, Trash2, Plus, Receipt, FileSignature
} 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 { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { useToast } from '@/hooks/use-toast';
import sutekiLogo from '@/assets/suteki-logo.png';
import AddContactModal from '@/components/dashboard/AddContactModal';
import { EditCompanyModal } from '@/components/dashboard/EditCompanyModal';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { StatusBadge } from '@/components/dashboard/StatusBadge';
import { normalizeStatus } from '@/lib/leadStatus';
import { EmptyState } from '@/components/dashboard/EmptyState';
import { fmtListDate } from '@/lib/dateFormat';

interface Company {
  id: string;
  name: string;
  domain: string | null;
  website: string | null;
  industry: string | null;
  address: string | null;
  street: string | null;
  postal_code: string | null;
  city: string | null;
  country: string | null;
  phone: string | null;
  notes: string | null;
  created_at: string;
}

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;
}

interface Lead {
  id: string;
  name: string;
  email: string;
  status: string;
  created_at: string;
  project_description: string | null;
  next_followup_date: string | null;
  contact_id: string | null;
  contact_name?: string | null;
}

export default function CompanyDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user, loading: authLoading, isSalesTeam } = useAuth();
  const { toast } = useToast();
  
  const [company, setCompany] = useState<Company | null>(null);
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [leads, setLeads] = useState<Lead[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddContactModal, setShowAddContactModal] = useState(false);
  const [showEditCompanyModal, setShowEditCompanyModal] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [showAllInquiries, setShowAllInquiries] = useState(false);

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

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

  const fetchCompanyData = async () => {
    if (!id) return;
    
    setIsLoading(true);
    
    // Fetch company
    const { data: companyData, error: companyError } = await supabase
      .from('companies')
      .select('*')
      .eq('id', id)
      .maybeSingle();

    if (companyError || !companyData) {
      console.error('Error fetching company:', companyError);
      toast({
        title: 'Fel',
        description: 'Kunde inte hämta företag',
        variant: 'destructive'
      });
              navigate('/dashboard/sales');
      return;
    }

    setCompany(companyData as Company);

    // Fetch contacts
    const { data: contactsData } = await supabase
      .from('contacts')
      .select('id, first_name, last_name, name, email, phone, direct_phone, mobile_phone, title')
      .eq('company_id', id)
      .order('created_at', { ascending: false });
    
    setContacts((contactsData || []) as Contact[]);

    // Fetch leads
    const { data: leadsData } = await supabase
      .from('leads')
      .select('id, name, email, status, created_at, project_description, next_followup_date, contact_id')
      .eq('company_id', id)
      .order('updated_at', { ascending: false });

    // Resolve contact names
    const contactIds = Array.from(new Set((leadsData || []).map((l: any) => l.contact_id).filter(Boolean)));
    let contactMap: Record<string, string> = {};
    if (contactIds.length > 0) {
      const { data: contactRows } = await supabase
        .from('contacts')
        .select('id, name, first_name, last_name, email')
        .in('id', contactIds as string[]);
      (contactRows || []).forEach((c: any) => {
        contactMap[c.id] =
          [c.first_name, c.last_name].filter(Boolean).join(' ') || c.name || c.email;
      });
    }

    const enriched: Lead[] = (leadsData || []).map((l: any) => ({
      ...l,
      contact_name: l.contact_id ? contactMap[l.contact_id] || l.name : l.name,
    }));
    setLeads(enriched);

    setIsLoading(false);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('sv-SE', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const handleDeleteCompany = async () => {
    if (!company) return;
    setDeleting(true);
    const { error } = await supabase.from('companies').delete().eq('id', company.id);
    setDeleting(false);
    if (error) {
      toast({ title: 'Kunde inte radera', description: error.message, variant: 'destructive' });
      return;
    }
    toast({ title: '🗑️ Företag raderat' });
    navigate('/dashboard/companies');
  };

  if (authLoading || isLoading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-6 py-8">
          <Skeleton className="h-8 w-48 mb-6" />
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 space-y-6">
              <Skeleton className="h-64" />
              <Skeleton className="h-96" />
            </div>
            <div className="space-y-6">
              <Skeleton className="h-48" />
              <Skeleton className="h-64" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!company) return null;

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <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-6 md:py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Company Info */}
            <Card>
              <CardHeader>
                 <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 min-w-0">
                   <CardTitle className="flex items-center gap-2 min-w-0 break-words">
                    <Building2 className="h-5 w-5" />
                    {company.name}
                  </CardTitle>
                   <div className="flex flex-wrap items-center gap-2">
                    <Button size="sm" variant="outline" onClick={() => navigate(`/dashboard/quotes/new?company=${company.id}`)}>
                      <FileSignature className="h-4 w-4 mr-1" /> Skapa offert
                    </Button>
                    <Button size="sm" onClick={() => navigate(`/dashboard/invoices/new?company=${company.id}`)}>
                      <Receipt className="h-4 w-4 mr-1" /> Skapa faktura
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => setShowEditCompanyModal(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={() => setShowDeleteDialog(true)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {company.domain && (
                  <div className="flex items-center gap-2 text-sm">
                    <Globe className="h-4 w-4 text-muted-foreground" />
                    <a 
                      href={`https://${company.domain}`}
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="text-accent hover:underline"
                    >
                      {company.domain}
                    </a>
                  </div>
                )}
                {company.website && (
                  <div className="flex items-center gap-2 text-sm">
                    <Globe className="h-4 w-4 text-muted-foreground" />
                    <a 
                      href={company.website} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="text-accent hover:underline"
                    >
                      {company.website}
                    </a>
                  </div>
                )}
                {company.industry && (
                  <div className="flex items-center gap-2 text-sm">
                    <Building2 className="h-4 w-4 text-muted-foreground" />
                    {company.industry}
                  </div>
                )}
                {company.phone && (
                  <div className="flex items-center gap-2 text-sm">
                    <Phone className="h-4 w-4 text-muted-foreground" />
                    <a href={`tel:${company.phone}`} className="hover:underline">
                      {company.phone}
                    </a>
                  </div>
                )}
                {(company.street || company.city || company.postal_code || company.country || company.address) && (
                  <div className="flex items-start gap-2 text-sm md:col-span-2">
                    <MapPin className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
                    <div className="leading-relaxed">
                      {company.street ? (
                        <>
                          {company.street && <div>{company.street}</div>}
                          {(company.postal_code || company.city) && (
                            <div>{[company.postal_code, company.city].filter(Boolean).join(' ')}</div>
                          )}
                          {company.country && <div>{company.country}</div>}
                        </>
                      ) : (
                        <div>{company.address}</div>
                      )}
                    </div>
                  </div>
                )}
                {company.notes && (
                  <div className="md:col-span-2 pt-4 border-t border-border">
                    <h4 className="text-sm font-medium mb-2">Anteckningar</h4>
                    <p className="text-sm text-muted-foreground">{company.notes}</p>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Förfrågningar */}
            <Card>
                <CardHeader>
                  <div className="flex items-center justify-between gap-3">
                    <CardTitle className="flex items-center gap-2">
                      <FileText className="h-5 w-5" />
                      Förfrågningar ({leads.length})
                    </CardTitle>
                    <Button
                      size="sm"
                      onClick={() => navigate(`/dashboard/leads/new?company=${company.id}`)}
                    >
                      <Plus className="h-4 w-4 mr-1" /> Nytt lead
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  {leads.length === 0 ? (
                    <EmptyState icon={FileText} title="Inga förfrågningar för detta företag" />
                  ) : (
                  <div className="divide-y divide-border -mx-2">
                    {(showAllInquiries ? leads : leads.slice(0, 3)).map((lead) => (
                      <Link
                        key={lead.id}
                        to={`/dashboard/leads/${lead.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">
                              {lead.project_description?.trim() || '(Ingen rubrik)'}
                            </div>
                            <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
                              <span className="truncate">{lead.contact_name || '—'}</span>
                              {lead.next_followup_date && (
                                <>
                                  <span className="text-muted-foreground">·</span>
                                  <span className="text-muted-foreground/70">
                                    {fmtListDate(lead.next_followup_date)}
                                  </span>
                                </>
                              )}
                            </div>
                          </div>
                          <StatusBadge status={normalizeStatus(lead.status)} className="shrink-0 text-[10px]" />
                        </div>
                      </Link>
                    ))}
                    {leads.length > 3 && (
                      <button
                        type="button"
                        onClick={() => setShowAllInquiries((v) => !v)}
                        className="w-full text-left px-3 pt-3 text-xs text-muted-foreground hover:text-accent transition-colors"
                      >
                        {showAllInquiries ? 'Visa färre' : `Visa alla förfrågningar (${leads.length}) →`}
                      </button>
                    )}
                  </div>
                  )}
                </CardContent>
            </Card>
          </div>

          {/* Sidebar - Contacts */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2 text-base">
                    <User className="h-5 w-5" />
                    Kontakter ({contacts.length})
                  </CardTitle>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => setShowAddContactModal(true)}
                  >
                    <UserPlus className="h-4 w-4 mr-1" />
                    Lägg till
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                {contacts.length === 0 ? (
                  <EmptyState icon={User} title="Inga kontakter ännu" />
                ) : (
                  <div className="space-y-4">
                    {contacts.map((contact) => {
                      const displayName = [contact.first_name, contact.last_name].filter(Boolean).join(' ') || contact.name || 'Okänd';
                      return (
                      <Link key={contact.id} to={`/dashboard/contacts/${contact.id}`} className="block p-3 bg-secondary/50 hover:bg-secondary rounded-lg transition-colors">
                        <div className="font-medium text-foreground">{displayName}</div>
                        {contact.title && (
                          <div className="text-xs text-muted-foreground">{contact.title}</div>
                        )}
                        <div className="flex items-center gap-2 text-sm mt-2">
                          <Mail className="h-3 w-3 text-muted-foreground" />
                          <span className="text-accent text-xs truncate">{contact.email}</span>
                        </div>
                        {contact.direct_phone && (
                          <div className="flex items-center gap-2 text-sm mt-1">
                            <Phone className="h-3 w-3 text-muted-foreground" />
                            <span className="text-xs">{contact.direct_phone}</span>
                            <span className="text-[10px] text-muted-foreground">direkt</span>
                          </div>
                        )}
                        {contact.mobile_phone && (
                          <div className="flex items-center gap-2 text-sm mt-1">
                            <Smartphone className="h-3 w-3 text-muted-foreground" />
                            <span className="text-xs">{contact.mobile_phone}</span>
                            <span className="text-[10px] text-muted-foreground">mobil</span>
                          </div>
                        )}
                        {!contact.direct_phone && !contact.mobile_phone && contact.phone && (
                          <div className="flex items-center gap-2 text-sm mt-1">
                            <Phone className="h-3 w-3 text-muted-foreground" />
                            <span className="text-xs">{contact.phone}</span>
                          </div>
                        )}
                      </Link>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Stats */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Statistik</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Förfrågningar</span>
                  <span className="font-medium">{leads.length}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Kontakter</span>
                  <span className="font-medium">{contacts.length}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Skapad</span>
                  <span>{formatDate(company.created_at)}</span>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </main>

      <AddContactModal
        open={showAddContactModal}
        onOpenChange={setShowAddContactModal}
        companyId={id!}
        onContactAdded={fetchCompanyData}
      />
      <EditCompanyModal
        open={showEditCompanyModal}
        onOpenChange={setShowEditCompanyModal}
        company={company}
        onSaved={fetchCompanyData}
      />
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Radera {company.name}?</AlertDialogTitle>
            <AlertDialogDescription>
              Detta tar bort företaget permanent. Kontakter och förfrågningar kopplade till företaget blir kvar men förlorar kopplingen. Åtgärden kan inte ångras.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Avbryt</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteCompany} disabled={deleting} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              {deleting ? 'Raderar...' : 'Radera'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
