import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { PageHeader } from '../../../../components/layout';
import { Button, StatsGrid, StatusCard, getStatusColor, SearchAndFilter, EmptyState } from '../../../../components/ui';
import { useTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import {
  Plus,
  Building2,
  Settings,
  Users,
  ArrowRight,
  Crown,
  Shield,
  Eye
} from 'lucide-react';

const OrganizationsPage: React.FC = () => {
  const { t } = useTranslation(['settings']);
  const navigate = useNavigate();
  const user = useAuthUser();
  const { currentTenant, availableTenants, switchTenant } = useTenant();
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [roleFilter, setRoleFilter] = useState('');

  const handleAddNewOrganization = () => {
    navigate('/app/onboarding?new=true');
  };

  const handleSwitchToTenant = async (tenantId: string) => {
    if (tenantId === currentTenant?.id) return;

    setIsLoading(true);
    await switchTenant(tenantId);
    setIsLoading(false);
  };

  const handleManageTenant = () => {
    navigate(`/app/database/bakery-config`);
  };

  const handleManageTeam = () => {
    navigate(`/app/database/team`);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('es-ES', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const isOwner = (ownerId: string) => user?.id === ownerId;

  // Filter organizations based on search and role
  const filteredTenants = useMemo(() => {
    let filtered = availableTenants || [];

    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      filtered = filtered.filter(tenant =>
        tenant.name.toLowerCase().includes(searchLower) ||
        tenant.business_type?.toLowerCase().includes(searchLower) ||
        tenant.city?.toLowerCase().includes(searchLower)
      );
    }

    if (roleFilter) {
      filtered = filtered.filter(tenant => {
        if (roleFilter === 'owner') return isOwner(tenant.owner_id);
        if (roleFilter === 'member') return !isOwner(tenant.owner_id);
        return true;
      });
    }

    return filtered;
  }, [availableTenants, searchTerm, roleFilter, user?.id]);

  // Calculate stats
  const stats = useMemo(() => [
    {
      title: 'Organizaciones Totales',
      value: availableTenants?.length || 0,
      variant: 'default' as const,
      icon: Building2,
    },
    {
      title: 'Como Propietario',
      value: availableTenants?.filter(t => isOwner(t.owner_id)).length || 0,
      variant: 'warning' as const,
      icon: Crown,
    },
    {
      title: 'Como Miembro',
      value: availableTenants?.filter(t => !isOwner(t.owner_id)).length || 0,
      variant: 'info' as const,
      icon: Shield,
    },
  ], [availableTenants, user?.id]);

  return (
    <div className="space-y-6">
      <PageHeader
        title="Organizaciones"
        description="Gestiona tus organizaciones y configuraciones"
        actions={[
          {
            id: "add-organization",
            label: "Nueva Organización",
            variant: "primary" as const,
            icon: Plus,
            onClick: handleAddNewOrganization,
            tooltip: "Crear nueva organización",
            size: "md"
          }
        ]}
      />

      {/* Stats Grid */}
      <StatsGrid
        stats={stats}
        columns={3}
      />

      {/* Search and Filter Controls */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Buscar por nombre, tipo o ciudad..."
        filters={[
          {
            key: 'role',
            label: 'Rol',
            type: 'dropdown',
            value: roleFilter,
            onChange: (value) => setRoleFilter(value as string),
            placeholder: 'Todos los roles',
            options: [
              { value: 'owner', label: 'Propietario' },
              { value: 'member', label: 'Miembro' }
            ]
          }
        ]}
      />

      {/* Organizations Grid */}
      {filteredTenants && filteredTenants.length > 0 ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredTenants.map((tenant) => {
            const isActive = currentTenant?.id === tenant.id;
            const isOwnerRole = isOwner(tenant.owner_id);

            const statusConfig = {
              color: isActive ? getStatusColor('completed') : getStatusColor('default'),
              text: isActive ? 'Activa' : 'Inactiva',
              icon: isOwnerRole ? Crown : Shield,
              isCritical: false,
              isHighlight: isActive
            };

            return (
              <StatusCard
                key={tenant.id}
                id={tenant.id}
                statusIndicator={statusConfig}
                title={tenant.name}
                subtitle={tenant.business_type || 'Organización'}
                primaryValue={isOwnerRole ? 'Propietario' : 'Miembro'}
                primaryValueLabel=""
                secondaryInfo={
                  tenant.city ? {
                    label: 'Ubicación',
                    value: tenant.city
                  } : undefined
                }
                metadata={[
                  `Creada ${formatDate(tenant.created_at)}`,
                  ...(tenant.address ? [tenant.address] : []),
                  ...(tenant.phone ? [tenant.phone] : [])
                ]}
                onClick={() => {
                  if (!isActive) {
                    handleSwitchToTenant(tenant.id);
                  }
                }}
                actions={[
                  // Primary action - Switch or View Dashboard
                  {
                    label: isActive ? 'Ver Dashboard' : 'Cambiar',
                    icon: isActive ? Eye : ArrowRight,
                    variant: isActive ? 'outline' : 'primary',
                    priority: 'primary',
                    onClick: () => {
                      if (isActive) {
                        navigate('/app/dashboard');
                      } else {
                        handleSwitchToTenant(tenant.id);
                      }
                    }
                  },
                  // Settings action
                  {
                    label: 'Configuración',
                    icon: Settings,
                    priority: 'secondary',
                    onClick: () => {
                      if (!isActive) {
                        handleSwitchToTenant(tenant.id);
                      }
                      handleManageTenant();
                    }
                  },
                  // Team management - only for owners
                  ...(isOwnerRole ? [{
                    label: 'Equipo',
                    icon: Users,
                    priority: 'secondary' as const,
                    highlighted: true,
                    onClick: () => {
                      if (!isActive) {
                        handleSwitchToTenant(tenant.id);
                      }
                      handleManageTeam();
                    }
                  }] : [])
                ]}
              />
            );
          })}
        </div>
      ) : (
        <EmptyState
          icon={Building2}
          title="No se encontraron organizaciones"
          description={searchTerm || roleFilter
            ? "Intenta ajustar los filtros de búsqueda"
            : "Crea tu primera organización para comenzar a usar Bakery IA"
          }
          actionLabel="Nueva Organización"
          actionIcon={Plus}
          onAction={handleAddNewOrganization}
        />
      )}
    </div>
  );
};

export default OrganizationsPage;