import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Package,
  Plus,
  MoreVertical,
  Eye,
  CheckCircle,
  XCircle,
  Calendar,
  RefreshCw,
  Search,
  Truck,
  ClipboardList,
} 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 { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { ConfirmModal } from '@components/organisms/Modal';
import { NoDataEmptyState, ErrorEmptyState } from '@components/templates/EmptyState';
import { usePurchaseReceipts } from '@features/purchases/hooks';
import type { PurchaseReceipt } from '@features/purchases/types';
import { formatDate } from '@utils/formatters';

type ReceiptStatus = 'draft' | 'done' | 'cancelled';

const statusLabels: Record<ReceiptStatus, string> = {
  draft: 'Borrador',
  done: 'Completado',
  cancelled: 'Cancelado',
};

const statusColors: Record<ReceiptStatus, string> = {
  draft: 'bg-gray-100 text-gray-700',
  done: 'bg-green-100 text-green-700',
  cancelled: 'bg-red-100 text-red-700',
};

// Helper function to get current date
const getToday = (): string => {
  const today = new Date().toISOString().split('T')[0];
  return today || '';
};

export function PurchaseReceiptsPage() {
  const navigate = useNavigate();
  const [selectedStatus, setSelectedStatus] = useState<ReceiptStatus | ''>('');
  const [searchTerm, setSearchTerm] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [receiptToConfirm, setReceiptToConfirm] = useState<PurchaseReceipt | null>(null);
  const [receiptToCancel, setReceiptToCancel] = useState<PurchaseReceipt | null>(null);

  const {
    receipts,
    total,
    page,
    totalPages,
    isLoading,
    error,
    setPage,
    refresh,
    confirmReceipt,
    cancelReceipt,
  } = usePurchaseReceipts({
    status: selectedStatus || undefined,
    search: searchTerm || undefined,
    dateFrom: dateFrom || undefined,
    dateTo: dateTo || undefined,
    limit: 20,
  });

  const getActionsMenu = (receipt: PurchaseReceipt): DropdownItem[] => {
    const items: DropdownItem[] = [
      {
        key: 'view',
        label: 'Ver detalle',
        icon: <Eye className="h-4 w-4" />,
        onClick: () => navigate(`/purchases/receipts/${receipt.id}`),
      },
    ];

    if (receipt.status === 'draft') {
      items.push({
        key: 'confirm',
        label: 'Validar recepcion',
        icon: <CheckCircle className="h-4 w-4" />,
        onClick: () => setReceiptToConfirm(receipt),
      });
      items.push({
        key: 'cancel',
        label: 'Cancelar',
        icon: <XCircle className="h-4 w-4" />,
        danger: true,
        onClick: () => setReceiptToCancel(receipt),
      });
    }

    return items;
  };

  const columns: Column<PurchaseReceipt>[] = [
    {
      key: 'receiptNumber',
      header: 'Recepcion',
      render: (receipt) => (
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-50">
            <Package className="h-5 w-5 text-green-600" />
          </div>
          <div>
            <div className="font-medium text-gray-900">{receipt.receiptNumber}</div>
            <div className="text-sm text-gray-500">OC: {receipt.purchaseOrderName || receipt.purchaseOrderId}</div>
          </div>
        </div>
      ),
    },
    {
      key: 'partner',
      header: 'Proveedor',
      render: (receipt) => (
        <div>
          <div className="text-sm text-gray-900">{receipt.partnerName || receipt.partnerId}</div>
        </div>
      ),
    },
    {
      key: 'date',
      header: 'Fecha Recepcion',
      sortable: true,
      render: (receipt) => (
        <span className="text-sm text-gray-600">
          {formatDate(receipt.receiptDate, 'short')}
        </span>
      ),
    },
    {
      key: 'items',
      header: 'Productos',
      render: (receipt) => (
        <div className="flex items-center gap-2">
          <ClipboardList className="h-4 w-4 text-gray-400" />
          <span className="text-sm text-gray-600">
            {receipt.lines?.length || 0} lineas
          </span>
        </div>
      ),
    },
    {
      key: 'status',
      header: 'Estado',
      render: (receipt) => (
        <span className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${statusColors[receipt.status]}`}>
          {statusLabels[receipt.status]}
        </span>
      ),
    },
    {
      key: 'actions',
      header: '',
      render: (receipt) => (
        <Dropdown
          trigger={
            <button className="rounded p-1 hover:bg-gray-100">
              <MoreVertical className="h-4 w-4 text-gray-500" />
            </button>
          }
          items={getActionsMenu(receipt)}
          align="right"
        />
      ),
    },
  ];

  const handleConfirm = async () => {
    if (receiptToConfirm) {
      await confirmReceipt(receiptToConfirm.id);
      setReceiptToConfirm(null);
    }
  };

  const handleCancel = async () => {
    if (receiptToCancel) {
      await cancelReceipt(receiptToCancel.id);
      setReceiptToCancel(null);
    }
  };

  // Calculate summary stats
  const draftCount = receipts.filter(r => r.status === 'draft').length;
  const doneCount = receipts.filter(r => r.status === 'done').length;
  const todayReceipts = receipts.filter(r => r.receiptDate === getToday()).length;
  const totalItems = receipts.reduce((sum, r) => sum + (r.lines?.length || 0), 0);

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

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs items={[
        { label: 'Compras', href: '/purchases' },
        { label: 'Recepciones' },
      ]} />

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Recepciones de Compra</h1>
          <p className="text-sm text-gray-500">
            Registra y valida la recepcion de productos de proveedores
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={refresh} disabled={isLoading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
            Actualizar
          </Button>
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            Nueva recepcion
          </Button>
        </div>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setSelectedStatus('draft')}>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-gray-100">
                <Package className="h-5 w-5 text-gray-600" />
              </div>
              <div>
                <div className="text-sm text-gray-500">Pendientes</div>
                <div className="text-xl font-bold text-gray-900">{draftCount}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setSelectedStatus('done')}>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-green-100">
                <CheckCircle className="h-5 w-5 text-green-600" />
              </div>
              <div>
                <div className="text-sm text-gray-500">Completadas</div>
                <div className="text-xl font-bold text-green-600">{doneCount}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-100">
                <Truck className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <div className="text-sm text-gray-500">Hoy</div>
                <div className="text-xl font-bold text-blue-600">{todayReceipts}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-100">
                <ClipboardList className="h-5 w-5 text-purple-600" />
              </div>
              <div>
                <div className="text-sm text-gray-500">Items Recibidos</div>
                <div className="text-xl font-bold text-purple-600">{totalItems}</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Lista de Recepciones</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* Filters */}
            <div className="flex flex-wrap items-center gap-4">
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                <input
                  type="text"
                  placeholder="Buscar recepciones..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full rounded-md border border-gray-300 py-2 pl-10 pr-4 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                />
              </div>

              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value as ReceiptStatus | '')}
                className="rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              >
                <option value="">Todos los estados</option>
                {Object.entries(statusLabels).map(([value, label]) => (
                  <option key={value} value={value}>{label}</option>
                ))}
              </select>

              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-gray-400" />
                <input
                  type="date"
                  value={dateFrom}
                  onChange={(e) => setDateFrom(e.target.value)}
                  className="rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                />
                <span className="text-gray-400">-</span>
                <input
                  type="date"
                  value={dateTo}
                  onChange={(e) => setDateTo(e.target.value)}
                  className="rounded-md border border-gray-300 px-3 py-2 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                />
              </div>

              {(selectedStatus || searchTerm || dateFrom || dateTo) && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setSelectedStatus('');
                    setSearchTerm('');
                    setDateFrom('');
                    setDateTo('');
                  }}
                >
                  Limpiar filtros
                </Button>
              )}
            </div>

            {/* Table */}
            {receipts.length === 0 && !isLoading ? (
              <NoDataEmptyState
                entityName="recepciones de compra"
              />
            ) : (
              <DataTable
                data={receipts}
                columns={columns}
                isLoading={isLoading}
                pagination={{
                  page,
                  totalPages,
                  total,
                  limit: 20,
                  onPageChange: setPage,
                }}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {/* Confirm Receipt Modal */}
      <ConfirmModal
        isOpen={!!receiptToConfirm}
        onClose={() => setReceiptToConfirm(null)}
        onConfirm={handleConfirm}
        title="Validar recepcion"
        message={`¿Validar la recepcion ${receiptToConfirm?.receiptNumber}? Esto actualizara el inventario.`}
        variant="success"
        confirmText="Validar"
      />

      {/* Cancel Receipt Modal */}
      <ConfirmModal
        isOpen={!!receiptToCancel}
        onClose={() => setReceiptToCancel(null)}
        onConfirm={handleCancel}
        title="Cancelar recepcion"
        message={`¿Cancelar la recepcion ${receiptToCancel?.receiptNumber}? Esta accion no se puede deshacer.`}
        variant="danger"
        confirmText="Cancelar recepcion"
      />
    </div>
  );
}

export default PurchaseReceiptsPage;
