import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useContact } from '@/api/hooks';
import { Tabs, TabItem } from '@/components/shared/Tabs';
import { Card } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { EmptyState } from '@/components/ui/EmptyState';
import { Skeleton } from '@/components/ui/Skeleton';
import { Avatar } from '@/components/ui/Avatar';
import { TagPicker } from '@/components/tags/TagPicker';
import { AddressList } from '@/components/AddressList';

export function ContactDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { data: contact, isLoading, isError } = useContact(id);

  if (isLoading) {
    return (
      <div className="p-6 max-w-7xl mx-auto" data-testid="contact-detail-page">
        <Skeleton className="h-8 w-64 mb-6" />
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Skeleton className="h-32" />
          <Skeleton className="h-32" />
        </div>
      </div>
    );
  }

  if (isError || !contact) {
    return (
      <div className="p-6 max-w-7xl mx-auto" data-testid="contact-detail-page">
        <EmptyState
          title={t('contacts.notFound')}
          action={<Button onClick={() => navigate('/contacts')}>{t('common.back')}</Button>}
        />
      </div>
    );
  }

  const companies = contact.companies ?? [];

  const overviewTab: TabItem = {
    key: 'overview',
    label: t('contacts.overview'),
    content: (
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Card title={t('contacts.firstName')}>
          <p className="text-secondary-900">{contact.first_name}</p>
        </Card>
        <Card title={t('contacts.lastName')}>
          <p className="text-secondary-900">{contact.last_name}</p>
        </Card>
        <Card title={t('contacts.email')}>
          {contact.email ? (
            <a href={`mailto:${contact.email}`} className="text-primary-600 hover:text-primary-700">{contact.email}</a>
          ) : <p className="text-secondary-500">—</p>}
        </Card>
        <Card title={t('contacts.phone')}>
          <p className="text-secondary-900">{contact.phone || '—'}</p>
        </Card>
        <Card title={t('contacts.position')}>
          <p className="text-secondary-900">{contact.position || '—'}</p>
        </Card>
      </div>
    ),
  };

  const companiesTab: TabItem = {
    key: 'companies',
    label: t('contacts.companies'),
    badge: companies.length,
    content: companies.length === 0 ? (
      <EmptyState title={t('contacts.noCompanies')} />
    ) : (
      <ul className="space-y-2" role="list">
        {companies.map((company) => (
          <li key={company.id}>
            <button
              onClick={() => navigate(`/companies/${company.id}`)}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-secondary-50 text-left min-h-touch"
            >
              <div className="w-10 h-10 rounded-lg bg-primary-50 flex items-center justify-center text-primary-600 font-semibold flex-shrink-0">
                {company.name.charAt(0).toUpperCase()}
              </div>
              <div className="flex-1 min-w-0">
                <p className="font-medium text-secondary-900">{company.name}</p>
                {company.industry && (
                  <p className="text-sm text-secondary-500">{company.industry}</p>
                )}
              </div>
              {company.email && (
                <Badge variant="info">{company.email}</Badge>
              )}
            </button>
          </li>
        ))}
      </ul>
    ),
  };

  const addressesTab: TabItem = {
    key: 'addresses',
    label: t('address.title'),
    content: (
      <AddressList entityType="contact" entityId={contact.id} />
    ),
  };

  const tagsTab: TabItem = {
    key: 'tags',
    label: t('tags.title'),
    content: (
      <TagPicker entityType="contact" entityId={contact.id} />
    ),
  };

  const filesTab: TabItem = {
    key: 'files',
    label: t('contacts.files'),
    content: <EmptyState title={t('contacts.noFiles')} />,
  };

  const activityTab: TabItem = {
    key: 'activity',
    label: t('contacts.activity'),
    content: <EmptyState title={t('contacts.noActivity')} />,
  };

  return (
    <div className="p-6 max-w-7xl mx-auto" data-testid="contact-detail-page">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => navigate('/contacts')} aria-label={t('common.back')}>
            ← {t('common.back')}
          </Button>
          <Avatar name={`${contact.first_name} ${contact.last_name}`} size="md" />
          <h1 className="text-2xl font-bold text-secondary-900">{contact.first_name} {contact.last_name}</h1>
        </div>
        <Button onClick={() => navigate(`/contacts/${contact.id}/edit`)}>
          {t('common.edit')}
        </Button>
      </div>
      <Tabs tabs={[overviewTab, companiesTab, addressesTab, tagsTab, filesTab, activityTab]} defaultKey="overview" />
    </div>
  );
}
