'use client';

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

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

  // ✅ 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 icon-flat" />
      : <Beaker className="h-8 w-8 icon-flat" />;
  };

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

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

  return (
    <div className="min-h-screen app-web-bg 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-semibold 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="surface-card p-6 transition-all text-left flex items-center gap-4 hover:border-primary/60"
            >
              <div className="p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary">
                {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 text-sm">
                Continue →
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}