'use client';

import { useState } from 'react';
import {
  Plus, Pencil, Trash2, Search, Mail, Phone, MapPin,
  Globe, Building2, UserPlus, X,
} from 'lucide-react';
import { Button } from '@/shared/components/ui/button';
import { Input } from '@/shared/components/ui/input';
import { Label } from '@/shared/components/ui/label';
import { Textarea } from '@/shared/components/ui/textarea';
import { Badge } from '@/shared/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/components/ui/card';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/shared/components/ui/select';
import type { AddressContact, ContactType, ContactPerson } from '../types';
import { useContacts } from '../hooks/use-contacts';
import { useTags } from '@/core/tagging';

const TYPE_LABELS: Record<ContactType, string> = {
  client: 'Client',
  supplier: 'Furnizor',
  institution: 'Instituție',
  collaborator: 'Colaborator',
  internal: 'Intern',
};

type ViewMode = 'list' | 'add' | 'edit';

export function AddressBookModule() {
  const { contacts, allContacts, loading, filters, updateFilter, addContact, updateContact, removeContact } = useContacts();
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [editingContact, setEditingContact] = useState<AddressContact | null>(null);

  const handleSubmit = async (data: Omit<AddressContact, 'id' | 'createdAt' | 'updatedAt'>) => {
    if (viewMode === 'edit' && editingContact) {
      await updateContact(editingContact.id, data);
    } else {
      await addContact(data);
    }
    setViewMode('list');
    setEditingContact(null);
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
        <Card><CardContent className="p-4"><p className="text-xs text-muted-foreground">Total</p><p className="text-2xl font-bold">{allContacts.length}</p></CardContent></Card>
        {(Object.keys(TYPE_LABELS) as ContactType[]).slice(0, 4).map((type) => (
          <Card key={type}><CardContent className="p-4">
            <p className="text-xs text-muted-foreground">{TYPE_LABELS[type]}</p>
            <p className="text-2xl font-bold">{allContacts.filter((c) => c.type === type).length}</p>
          </CardContent></Card>
        ))}
      </div>

      {viewMode === 'list' && (
        <>
          <div className="flex flex-wrap items-center gap-3">
            <div className="relative min-w-[200px] flex-1">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Caută contact..." value={filters.search} onChange={(e) => updateFilter('search', e.target.value)} className="pl-9" />
            </div>
            <Select value={filters.type} onValueChange={(v) => updateFilter('type', v as ContactType | 'all')}>
              <SelectTrigger className="w-[150px]"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toate tipurile</SelectItem>
                {(Object.keys(TYPE_LABELS) as ContactType[]).map((t) => (
                  <SelectItem key={t} value={t}>{TYPE_LABELS[t]}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button onClick={() => setViewMode('add')} className="shrink-0">
              <Plus className="mr-1.5 h-4 w-4" /> Adaugă
            </Button>
          </div>

          {loading ? (
            <p className="py-8 text-center text-sm text-muted-foreground">Se încarcă...</p>
          ) : contacts.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">Niciun contact găsit.</p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {contacts.map((contact) => (
                <ContactCard
                  key={contact.id}
                  contact={contact}
                  onEdit={() => { setEditingContact(contact); setViewMode('edit'); }}
                  onDelete={() => removeContact(contact.id)}
                />
              ))}
            </div>
          )}
        </>
      )}

      {(viewMode === 'add' || viewMode === 'edit') && (
        <Card>
          <CardHeader><CardTitle>{viewMode === 'edit' ? 'Editare contact' : 'Contact nou'}</CardTitle></CardHeader>
          <CardContent>
            <ContactForm
              initial={editingContact ?? undefined}
              onSubmit={handleSubmit}
              onCancel={() => { setViewMode('list'); setEditingContact(null); }}
            />
          </CardContent>
        </Card>
      )}
    </div>
  );
}

// ── Contact Card ──

function ContactCard({ contact, onEdit, onDelete }: {
  contact: AddressContact;
  onEdit: () => void;
  onDelete: () => void;
}) {
  return (
    <Card className="group relative">
      <CardContent className="p-4">
        <div className="absolute right-2 top-2 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={onEdit}>
            <Pencil className="h-3.5 w-3.5" />
          </Button>
          <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={onDelete}>
            <Trash2 className="h-3.5 w-3.5" />
          </Button>
        </div>
        <div className="space-y-2">
          <div>
            <p className="font-medium">{contact.name}</p>
            <div className="flex flex-wrap items-center gap-1.5">
              {contact.company && <p className="text-xs text-muted-foreground">{contact.company}</p>}
              <Badge variant="outline" className="text-[10px]">{TYPE_LABELS[contact.type]}</Badge>
              {contact.department && (
                <Badge variant="secondary" className="text-[10px]">{contact.department}</Badge>
              )}
            </div>
            {contact.role && (
              <p className="text-xs text-muted-foreground italic">{contact.role}</p>
            )}
          </div>
          {contact.email && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="h-3 w-3 shrink-0" /><span className="truncate">{contact.email}</span>
            </div>
          )}
          {contact.email2 && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="h-3 w-3 shrink-0" /><span className="truncate">{contact.email2}</span>
            </div>
          )}
          {contact.phone && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Phone className="h-3 w-3 shrink-0" /><span>{contact.phone}</span>
            </div>
          )}
          {contact.phone2 && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Phone className="h-3 w-3 shrink-0" /><span>{contact.phone2}</span>
            </div>
          )}
          {contact.address && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <MapPin className="h-3 w-3 shrink-0" /><span className="truncate">{contact.address}</span>
            </div>
          )}
          {contact.website && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Globe className="h-3 w-3 shrink-0" /><span className="truncate">{contact.website}</span>
            </div>
          )}
          {contact.contactPersons.length > 0 && (
            <div className="mt-1 border-t pt-1">
              <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1">
                Persoane de contact ({contact.contactPersons.length})
              </p>
              {contact.contactPersons.slice(0, 2).map((cp, i) => (
                <p key={i} className="text-xs text-muted-foreground">
                  {cp.name}{cp.role ? ` — ${cp.role}` : ''}
                </p>
              ))}
              {contact.contactPersons.length > 2 && (
                <p className="text-[10px] text-muted-foreground">
                  +{contact.contactPersons.length - 2} altele
                </p>
              )}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

// ── Contact Form ──

function ContactForm({ initial, onSubmit, onCancel }: {
  initial?: AddressContact;
  onSubmit: (data: Omit<AddressContact, 'id' | 'createdAt' | 'updatedAt'>) => void;
  onCancel: () => void;
}) {
  const { tags: projectTags } = useTags('project');
  const [name, setName] = useState(initial?.name ?? '');
  const [company, setCompany] = useState(initial?.company ?? '');
  const [type, setType] = useState<ContactType>(initial?.type ?? 'client');
  const [email, setEmail] = useState(initial?.email ?? '');
  const [email2, setEmail2] = useState(initial?.email2 ?? '');
  const [phone, setPhone] = useState(initial?.phone ?? '');
  const [phone2, setPhone2] = useState(initial?.phone2 ?? '');
  const [address, setAddress] = useState(initial?.address ?? '');
  const [department, setDepartment] = useState(initial?.department ?? '');
  const [role, setRole] = useState(initial?.role ?? '');
  const [website, setWebsite] = useState(initial?.website ?? '');
  const [notes, setNotes] = useState(initial?.notes ?? '');
  const [projectIds, setProjectIds] = useState<string[]>(initial?.projectIds ?? []);
  const [contactPersons, setContactPersons] = useState<ContactPerson[]>(
    initial?.contactPersons ?? []
  );

  const addContactPerson = () => {
    setContactPersons([...contactPersons, { name: '', role: '', email: '', phone: '' }]);
  };

  const updateContactPerson = (index: number, field: keyof ContactPerson, value: string) => {
    setContactPersons(contactPersons.map((cp, i) =>
      i === index ? { ...cp, [field]: value } : cp
    ));
  };

  const removeContactPerson = (index: number) => {
    setContactPersons(contactPersons.filter((_, i) => i !== index));
  };

  const toggleProject = (projectId: string) => {
    setProjectIds((prev) =>
      prev.includes(projectId) ? prev.filter((id) => id !== projectId) : [...prev, projectId]
    );
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit({
          name, company, type, email, email2, phone, phone2,
          address, department, role, website, notes,
          projectIds,
          contactPersons: contactPersons.filter((cp) => cp.name.trim()),
          tags: initial?.tags ?? [],
          visibility: initial?.visibility ?? 'all',
        });
      }}
      className="space-y-4"
    >
      {/* Row 1: Name + Company + Type */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div><Label>Nume *</Label><Input value={name} onChange={(e) => setName(e.target.value)} className="mt-1" required /></div>
        <div><Label>Companie/Organizație</Label><Input value={company} onChange={(e) => setCompany(e.target.value)} className="mt-1" /></div>
        <div><Label>Tip</Label>
          <Select value={type} onValueChange={(v) => setType(v as ContactType)}>
            <SelectTrigger className="mt-1"><SelectValue /></SelectTrigger>
            <SelectContent>
              {(Object.keys(TYPE_LABELS) as ContactType[]).map((t) => (
                <SelectItem key={t} value={t}>{TYPE_LABELS[t]}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Row 2: Department + Role + Website */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div><Label>Departament</Label><Input value={department} onChange={(e) => setDepartment(e.target.value)} className="mt-1" /></div>
        <div><Label>Funcție/Rol</Label><Input value={role} onChange={(e) => setRole(e.target.value)} className="mt-1" /></div>
        <div><Label>Website</Label><Input type="url" value={website} onChange={(e) => setWebsite(e.target.value)} className="mt-1" placeholder="https://" /></div>
      </div>

      {/* Row 3: Emails + Phones */}
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="grid gap-2">
          <div><Label>Email principal</Label><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="mt-1" /></div>
          <div><Label>Email secundar</Label><Input type="email" value={email2} onChange={(e) => setEmail2(e.target.value)} className="mt-1" /></div>
        </div>
        <div className="grid gap-2">
          <div><Label>Telefon principal</Label><Input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} className="mt-1" /></div>
          <div><Label>Telefon secundar</Label><Input type="tel" value={phone2} onChange={(e) => setPhone2(e.target.value)} className="mt-1" /></div>
        </div>
      </div>

      {/* Address */}
      <div><Label>Adresă</Label><Input value={address} onChange={(e) => setAddress(e.target.value)} className="mt-1" /></div>

      {/* Project links */}
      {projectTags.length > 0 && (
        <div>
          <Label>Proiecte asociate</Label>
          <div className="mt-1.5 flex flex-wrap gap-1.5">
            {projectTags.map((pt) => (
              <button
                key={pt.id}
                type="button"
                onClick={() => toggleProject(pt.id)}
                className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
                  projectIds.includes(pt.id)
                    ? 'border-primary bg-primary/10 text-primary'
                    : 'border-muted-foreground/30 text-muted-foreground hover:border-primary/50'
                }`}
              >
                {pt.projectCode ? `${pt.projectCode} ` : ''}{pt.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Contact Persons */}
      <div>
        <div className="flex items-center justify-between">
          <Label>Persoane de contact</Label>
          <Button type="button" variant="outline" size="sm" onClick={addContactPerson}>
            <UserPlus className="mr-1 h-3.5 w-3.5" /> Adaugă persoană
          </Button>
        </div>
        {contactPersons.length > 0 && (
          <div className="mt-2 space-y-2">
            {contactPersons.map((cp, i) => (
              <div key={i} className="flex flex-wrap items-start gap-2 rounded border p-2">
                <Input placeholder="Nume" value={cp.name} onChange={(e) => updateContactPerson(i, 'name', e.target.value)} className="min-w-[150px] flex-1 text-sm" />
                <Input placeholder="Funcție" value={cp.role} onChange={(e) => updateContactPerson(i, 'role', e.target.value)} className="w-[140px] text-sm" />
                <Input placeholder="Email" value={cp.email} onChange={(e) => updateContactPerson(i, 'email', e.target.value)} className="w-[180px] text-sm" />
                <Input placeholder="Telefon" value={cp.phone} onChange={(e) => updateContactPerson(i, 'phone', e.target.value)} className="w-[140px] text-sm" />
                <Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0 text-destructive" onClick={() => removeContactPerson(i)}>
                  <X className="h-3.5 w-3.5" />
                </Button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Notes */}
      <div><Label>Note</Label><Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} className="mt-1" /></div>

      <div className="flex justify-end gap-2 pt-2">
        <Button type="button" variant="outline" onClick={onCancel}>Anulează</Button>
        <Button type="submit">{initial ? 'Actualizează' : 'Adaugă'}</Button>
      </div>
    </form>
  );
}
