import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeft,
  Edit,
  Trash2,
  Mail,
  Phone,
  Globe,
  FileText,
  UserCheck,
  UserX,
  Building2,
  User,
} from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Spinner } from '@components/atoms/Spinner';
import { Card, CardHeader, CardTitle, CardContent } from '@components/molecules/Card';
import { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { ConfirmModal } from '@components/organisms/Modal';
import { useToast } from '@components/organisms/Toast';
import { ErrorEmptyState } from '@components/templates/EmptyState';
import { usePartner } from '@features/partners/hooks';
import { partnersApi } from '@features/partners/api';
import { PartnerTypeBadge } from '@features/partners/components/PartnerTypeBadge';
import { PartnerStatusBadge } from '@features/partners/components/PartnerStatusBadge';
import { formatDate } from '@utils/formatters';

export function PartnerDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { partner, isLoading, error, refresh } = usePartner(id);

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showToggleModal, setShowToggleModal] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);

  const handleDelete = async () => {
    if (!id) return;
    setIsProcessing(true);
    try {
      await partnersApi.delete(id);
      showToast({
        type: 'success',
        title: 'Partner eliminado',
        message: 'El partner ha sido eliminado exitosamente.',
      });
      navigate('/partners');
    } catch {
      showToast({
        type: 'error',
        title: 'Error',
        message: 'No se pudo eliminar el partner.',
      });
    } finally {
      setIsProcessing(false);
      setShowDeleteModal(false);
    }
  };

  const handleToggleStatus = async () => {
    if (!id || !partner) return;
    setIsProcessing(true);
    try {
      if (partner.active) {
        await partnersApi.deactivate(id);
        showToast({
          type: 'success',
          title: 'Partner desactivado',
          message: 'El partner ha sido desactivado.',
        });
      } else {
        await partnersApi.activate(id);
        showToast({
          type: 'success',
          title: 'Partner activado',
          message: 'El partner ha sido activado.',
        });
      }
      refresh();
    } catch {
      showToast({
        type: 'error',
        title: 'Error',
        message: 'No se pudo cambiar el estado del partner.',
      });
    } finally {
      setIsProcessing(false);
      setShowToggleModal(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Spinner size="lg" />
      </div>
    );
  }

  if (error || !partner) {
    return (
      <div className="p-6">
        <ErrorEmptyState
          title="Partner no encontrado"
          description="No se pudo cargar la información del partner."
          onRetry={refresh}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[
          { label: 'Partners', href: '/partners' },
          { label: partner.name },
        ]}
      />

      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={() => navigate('/partners')}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Volver
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Detalle de partner</h1>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => navigate(`/partners/${id}/edit`)}>
            <Edit className="mr-2 h-4 w-4" />
            Editar
          </Button>
          <Button variant="danger" onClick={() => setShowDeleteModal(true)}>
            <Trash2 className="mr-2 h-4 w-4" />
            Eliminar
          </Button>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Partner info card */}
        <div className="lg:col-span-1">
          <Card>
            <CardContent className="pt-6">
              <div className="flex flex-col items-center text-center">
                <div className="flex h-20 w-20 items-center justify-center rounded-xl bg-primary-100">
                  {partner.partnerType === 'company' ? (
                    <Building2 className="h-10 w-10 text-primary-600" />
                  ) : (
                    <User className="h-10 w-10 text-primary-600" />
                  )}
                </div>
                <h2 className="mt-4 text-xl font-semibold text-gray-900">
                  {partner.name}
                </h2>
                {partner.legalName && (
                  <p className="text-sm text-gray-500">{partner.legalName}</p>
                )}

                <div className="mt-3 flex flex-wrap justify-center gap-2">
                  <PartnerTypeBadge
                    type={partner.partnerType}
                    isCustomer={partner.isCustomer}
                    isSupplier={partner.isSupplier}
                  />
                  <PartnerStatusBadge active={partner.active} />
                </div>

                <div className="mt-6 w-full space-y-3 text-left">
                  {partner.email && (
                    <div className="flex items-center gap-3 text-sm">
                      <Mail className="h-4 w-4 text-gray-400" />
                      <a href={`mailto:${partner.email}`} className="text-primary-600 hover:underline">
                        {partner.email}
                      </a>
                    </div>
                  )}
                  {partner.phone && (
                    <div className="flex items-center gap-3 text-sm">
                      <Phone className="h-4 w-4 text-gray-400" />
                      <span>{partner.phone}</span>
                    </div>
                  )}
                  {partner.website && (
                    <div className="flex items-center gap-3 text-sm">
                      <Globe className="h-4 w-4 text-gray-400" />
                      <a href={partner.website} target="_blank" rel="noopener noreferrer" className="text-primary-600 hover:underline">
                        {partner.website}
                      </a>
                    </div>
                  )}
                </div>

                <div className="mt-6 w-full space-y-2">
                  <Button
                    variant="outline"
                    className="w-full"
                    onClick={() => setShowToggleModal(true)}
                  >
                    {partner.active ? (
                      <>
                        <UserX className="mr-2 h-4 w-4" />
                        Desactivar
                      </>
                    ) : (
                      <>
                        <UserCheck className="mr-2 h-4 w-4" />
                        Activar
                      </>
                    )}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Details */}
        <div className="space-y-6 lg:col-span-2">
          {/* Fiscal Info */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                Información fiscal
              </CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-4 sm:grid-cols-2">
                <div>
                  <dt className="text-sm text-gray-500">RFC / Tax ID</dt>
                  <dd className="font-medium text-gray-900">{partner.taxId || 'No especificado'}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Idioma</dt>
                  <dd className="font-medium text-gray-900">
                    {partner.language === 'es' ? 'Español' : partner.language === 'en' ? 'English' : partner.language}
                  </dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Moneda</dt>
                  <dd className="font-medium text-gray-900">{partner.currencyCode || 'MXN'}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Empresa asociada</dt>
                  <dd className="font-medium text-gray-900">{partner.companyName || 'Ninguna'}</dd>
                </div>
              </dl>
            </CardContent>
          </Card>

          {/* Notes */}
          {(partner.notes || partner.internalNotes) && (
            <Card>
              <CardHeader>
                <CardTitle>Notas</CardTitle>
              </CardHeader>
              <CardContent>
                <dl className="space-y-4">
                  {partner.notes && (
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Notas públicas</dt>
                      <dd className="mt-1 whitespace-pre-wrap text-gray-900">{partner.notes}</dd>
                    </div>
                  )}
                  {partner.internalNotes && (
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Notas internas</dt>
                      <dd className="mt-1 whitespace-pre-wrap text-gray-900">{partner.internalNotes}</dd>
                    </div>
                  )}
                </dl>
              </CardContent>
            </Card>
          )}

          {/* System Info */}
          <Card>
            <CardHeader>
              <CardTitle>Información del sistema</CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-4 sm:grid-cols-2">
                <div>
                  <dt className="text-sm text-gray-500">ID</dt>
                  <dd className="font-mono text-sm text-gray-900">{partner.id}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Tenant ID</dt>
                  <dd className="font-mono text-sm text-gray-900">{partner.tenantId}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Creado</dt>
                  <dd className="text-gray-900">{formatDate(partner.createdAt, 'full')}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Actualizado</dt>
                  <dd className="text-gray-900">
                    {partner.updatedAt ? formatDate(partner.updatedAt, 'full') : '-'}
                  </dd>
                </div>
              </dl>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Modals */}
      <ConfirmModal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        onConfirm={handleDelete}
        title="Eliminar partner"
        message={`¿Estás seguro de que deseas eliminar a ${partner.name}? Esta acción no se puede deshacer.`}
        variant="danger"
        confirmText="Eliminar"
        isLoading={isProcessing}
      />

      <ConfirmModal
        isOpen={showToggleModal}
        onClose={() => setShowToggleModal(false)}
        onConfirm={handleToggleStatus}
        title={partner.active ? 'Desactivar partner' : 'Activar partner'}
        message={
          partner.active
            ? `¿Deseas desactivar a ${partner.name}?`
            : `¿Deseas activar a ${partner.name}?`
        }
        variant={partner.active ? 'warning' : 'success'}
        confirmText={partner.active ? 'Desactivar' : 'Activar'}
        isLoading={isProcessing}
      />
    </div>
  );
}

export default PartnerDetailPage;
