'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { Building2, Beaker } from 'lucide-react';

export default function SelectOrganizationPage() {
  const { organizations, selectOrganization, isLoading } = useAuth();
  const router = useRouter();

  // ✅ Auto-redirect if only one organization
  useEffect(() => {
    if (!isLoading && organizations.length === 1) {
      selectOrganization(organizations[0].id);
    }
  }, [organizations, isLoading]);

  const getIcon = (type: string) => {
    return type === 'CLINIC'
      ? <Building2 className="h-8 w-8" />
      : <Beaker className="h-8 w-8" />;
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p className="text-text-secondary">Loading organizations...</p>
      </div>
    );
  }

  if (!organizations.length) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <p className="text-text-secondary">No organizations found.</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background-secondary flex items-center justify-center p-4">
      <div className="max-w-2xl w-full">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-text-primary">
            Choose Organization
          </h1>
          <p className="text-text-secondary mt-2">
            You have access to multiple organizations. Select one to continue.
          </p>
        </div>

        <div className="grid gap-4">
          {organizations.map((org) => (
            <button
              key={org.id}
              onClick={() => selectOrganization(org.id)}
              className="bg-white p-6 rounded-xl shadow-sm border border-border hover:border-primary-300 hover:shadow-md transition-all text-left flex items-center gap-4"
            >
              <div className="p-3 bg-primary-50 rounded-lg text-primary-600">
                {getIcon(org.type)}
              </div>

              <div className="flex-1">
                <h3 className="text-lg font-semibold text-text-primary">
                  {org.name}
                </h3>
                <p className="text-sm text-text-secondary">
                  {org.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab'}
                </p>
              </div>

              <div className="text-primary-600 text-sm">
                Continue →
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}