import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Plus,
  MoreVertical,
  Eye,
  Edit,
  Trash2,
  UserCheck,
  UserX,
  Mail,
} from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Card, CardHeader, CardTitle, CardContent } from '@components/molecules/Card';
import { DataTable, type Column } from '@components/organisms/DataTable';
import { Dropdown, type DropdownItem } from '@components/organisms/Dropdown';
import { ConfirmModal } from '@components/organisms/Modal';
import { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { NoDataEmptyState, ErrorEmptyState } from '@components/templates/EmptyState';
import { usePartners } from '@features/partners/hooks';
import { PartnerFiltersPanel } from '@features/partners/components/PartnerFiltersPanel';
import { PartnerTypeBadge } from '@features/partners/components/PartnerTypeBadge';
import { PartnerStatusBadge } from '@features/partners/components/PartnerStatusBadge';
import type { Partner } from '@features/partners/types';
import { formatDate } from '@utils/formatters';

export function PartnersListPage() {
  const navigate = useNavigate();
  const [partnerToDelete, setPartnerToDelete] = useState<Partner | null>(null);
  const [partnerToToggle, setPartnerToToggle] = useState<{ partner: Partner; action: 'activate' | 'deactivate' } | null>(null);

  const {
    partners,
    total,
    page,
    totalPages,
    isLoading,
    error,
    filters,
    setFilters,
    deletePartner,
    activatePartner,
    deactivatePartner,
    refresh,
  } = usePartners({ page: 1, limit: 10 });

  const getActionsMenu = (partner: Partner): DropdownItem[] => {
    const items: DropdownItem[] = [
      {
        key: 'view',
        label: 'Ver detalle',
        icon: <Eye className="h-4 w-4" />,
        onClick: () => navigate(`/partners/${partner.id}`),
      },
      {
        key: 'edit',
        label: 'Editar',
        icon: <Edit className="h-4 w-4" />,
        onClick: () => navigate(`/partners/${partner.id}/edit`),
      },
    ];

    if (partner.email) {
      items.push({
        key: 'email',
        label: 'Enviar email',
        icon: <Mail className="h-4 w-4" />,
        onClick: () => window.location.href = `mailto:${partner.email}`,
      });
    }

    if (partner.active) {
      items.push({
        key: 'deactivate',
        label: 'Desactivar',
        icon: <UserX className="h-4 w-4" />,
        onClick: () => setPartnerToToggle({ partner, action: 'deactivate' }),
      });
    } else {
      items.push({
        key: 'activate',
        label: 'Activar',
        icon: <UserCheck className="h-4 w-4" />,
        onClick: () => setPartnerToToggle({ partner, action: 'activate' }),
      });
    }

    items.push({
      key: 'delete',
      label: 'Eliminar',
      icon: <Trash2 className="h-4 w-4" />,
      danger: true,
      onClick: () => setPartnerToDelete(partner),
    });

    return items;
  };

  const columns: Column<Partner>[] = [
    {
      key: 'partner',
      header: 'Partner',
      render: (partner) => (
        <div>
          <div className="font-medium text-gray-900">{partner.name}</div>
          <div className="text-sm text-gray-500">{partner.email || '-'}</div>
        </div>
      ),
    },
    {
      key: 'type',
      header: 'Tipo',
      render: (partner) => (
        <PartnerTypeBadge
          type={partner.partnerType}
          isCustomer={partner.isCustomer}
          isSupplier={partner.isSupplier}
        />
      ),
    },
    {
      key: 'taxId',
      header: 'RFC',
      render: (partner) => (
        <span className="text-sm text-gray-600">{partner.taxId || '-'}</span>
      ),
    },
    {
      key: 'phone',
      header: 'Teléfono',
      render: (partner) => (
        <span className="text-sm text-gray-600">{partner.phone || partner.mobile || '-'}</span>
      ),
    },
    {
      key: 'status',
      header: 'Estado',
      render: (partner) => <PartnerStatusBadge active={partner.active} />,
    },
    {
      key: 'createdAt',
      header: 'Creado',
      sortable: true,
      render: (partner) => (
        <span className="text-sm text-gray-500">
          {formatDate(partner.createdAt, 'short')}
        </span>
      ),
    },
    {
      key: 'actions',
      header: '',
      render: (partner) => (
        <Dropdown
          trigger={
            <button className="rounded p-1 hover:bg-gray-100">
              <MoreVertical className="h-4 w-4 text-gray-500" />
            </button>
          }
          items={getActionsMenu(partner)}
          align="right"
        />
      ),
    },
  ];

  const handlePageChange = (newPage: number) => {
    setFilters({ ...filters, page: newPage });
  };

  const handleSort = (key: string) => {
    const newOrder = filters.sortBy === key && filters.sortOrder === 'asc' ? 'desc' : 'asc';
    setFilters({ ...filters, sortBy: key, sortOrder: newOrder });
  };

  const handleDeleteConfirm = async () => {
    if (partnerToDelete) {
      await deletePartner(partnerToDelete.id);
      setPartnerToDelete(null);
    }
  };

  const handleToggleConfirm = async () => {
    if (partnerToToggle) {
      if (partnerToToggle.action === 'activate') {
        await activatePartner(partnerToToggle.partner.id);
      } else {
        await deactivatePartner(partnerToToggle.partner.id);
      }
      setPartnerToToggle(null);
    }
  };

  if (error) {
    return (
      <div className="p-6">
        <ErrorEmptyState onRetry={refresh} />
      </div>
    );
  }

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

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Partners</h1>
          <p className="text-sm text-gray-500">
            Gestiona clientes, proveedores y contactos
          </p>
        </div>
        <Button onClick={() => navigate('/partners/new')}>
          <Plus className="mr-2 h-4 w-4" />
          Nuevo partner
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Lista de partners</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <PartnerFiltersPanel
              filters={filters}
              onFiltersChange={setFilters}
            />

            {partners.length === 0 && !isLoading ? (
              <NoDataEmptyState
                entityName="partners"
                onCreateNew={() => navigate('/partners/new')}
              />
            ) : (
              <DataTable
                data={partners}
                columns={columns}
                isLoading={isLoading}
                pagination={{
                  page,
                  totalPages,
                  total,
                  limit: filters.limit || 10,
                  onPageChange: handlePageChange,
                }}
                sorting={{
                  sortBy: filters.sortBy || null,
                  sortOrder: (filters.sortOrder as 'asc' | 'desc') || 'asc',
                  onSort: handleSort,
                }}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {/* Delete confirmation modal */}
      <ConfirmModal
        isOpen={!!partnerToDelete}
        onClose={() => setPartnerToDelete(null)}
        onConfirm={handleDeleteConfirm}
        title="Eliminar partner"
        message={`¿Estás seguro de que deseas eliminar a ${partnerToDelete?.name}? Esta acción no se puede deshacer.`}
        variant="danger"
        confirmText="Eliminar"
      />

      {/* Activate/Deactivate confirmation modal */}
      <ConfirmModal
        isOpen={!!partnerToToggle}
        onClose={() => setPartnerToToggle(null)}
        onConfirm={handleToggleConfirm}
        title={partnerToToggle?.action === 'activate' ? 'Activar partner' : 'Desactivar partner'}
        message={
          partnerToToggle?.action === 'activate'
            ? `¿Deseas activar a ${partnerToToggle?.partner.name}?`
            : `¿Deseas desactivar a ${partnerToToggle?.partner.name}?`
        }
        variant={partnerToToggle?.action === 'activate' ? 'success' : 'warning'}
        confirmText={partnerToToggle?.action === 'activate' ? 'Activar' : 'Desactivar'}
      />
    </div>
  );
}

export default PartnersListPage;
