'use client';

import { useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { canCreateOrganizationFromCurrentOrg } from '@/components/shared/permissions';
import { Building2, Beaker, Mail } from 'lucide-react';
import { Input } from '@/components/ui/shared/Input';
import { Button } from '@/components/ui/shared/Button';

export function OrganizationSelectorContent() {
  const t = useTranslations('organizations');
  const tAuth = useTranslations('auth');
  const tCommon = useTranslations('common');
  const tErrors = useTranslations('errors');
  const {
    organizations,
    currentOrganization,
    selectOrganization,
    createOrganization,
    isLoading,
    apiError,
    clearError,
  } = useAuth();
  const canCreateOrganization = useMemo(
    () => canCreateOrganizationFromCurrentOrg(currentOrganization),
    [currentOrganization],
  );
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [organizationName, setOrganizationName] = useState('');
  const [organizationEmail, setOrganizationEmail] = useState('');
  const [organizationType, setOrganizationType] = useState<'CLINIC' | 'LAB'>('CLINIC');

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

  const getTypeLabel = (type: string) =>
    type === 'CLINIC' ? tAuth('dentalClinic') : tAuth('dentalLab');

  const handleCreateOrganization = async () => {
    try {
      clearError();
      const createdId = await createOrganization(
        organizationName.trim(),
        organizationEmail.trim(),
        organizationType,
      );
      setOrganizationName('');
      setOrganizationEmail('');
      setOrganizationType('CLINIC');
      setIsCreateOpen(false);
      await selectOrganization(createdId);
    } catch {
      // handled by auth context
    }
  };

  if (isLoading) {
    return <p className="text-text-secondary">{tCommon('loadingEllipsis')}</p>;
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-semibold text-text-primary">{t('selectorTitle')}</h1>
          <p className="text-text-secondary mt-2">
            {canCreateOrganization ? t('selectorSubtitleWithCreate') : t('selectorSubtitleSelectOnly')}
          </p>
        </div>
        {canCreateOrganization && (
          <Button
            type="button"
            variant={isCreateOpen ? 'outline' : 'primary'}
            className="w-full sm:w-auto shrink-0"
            onClick={() => {
              clearError();
              setIsCreateOpen((prev) => !prev);
            }}
          >
            {isCreateOpen ? tCommon('cancel') : t('createOrganization')}
          </Button>
        )}
      </div>

      {apiError && (
        <div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
          <p className="text-sm text-red-600">{getUserFacingError(apiError, tErrors)}</p>
        </div>
      )}

      {canCreateOrganization && isCreateOpen && (
        <div className="surface-card p-4 sm:p-6 space-y-4">
          <Input
            label={tAuth('organizationName')}
            value={organizationName}
            onChange={(event) => setOrganizationName(event.target.value)}
            placeholder={tAuth('organizationNamePlaceholder')}
            icon={<Building2 className="h-5 w-5 icon-flat" />}
          />
          <Input
            label={tAuth('organizationEmail')}
            value={organizationEmail}
            onChange={(event) => setOrganizationEmail(event.target.value)}
            placeholder={tAuth('organizationEmailPlaceholder')}
            type="email"
            icon={<Mail className="h-5 w-5 icon-flat" />}
          />
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              {tAuth('organizationType')}
            </label>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <button
                type="button"
                onClick={() => setOrganizationType('CLINIC')}
                className={`p-3 border rounded-[var(--radius-md)] text-sm ${
                  organizationType === 'CLINIC'
                    ? 'border-primary/60 bg-primary-soft text-text-primary'
                    : 'border-border text-text-secondary hover:border-border-strong'
                }`}
              >
                {tAuth('dentalClinic')}
              </button>
              <button
                type="button"
                onClick={() => setOrganizationType('LAB')}
                className={`p-3 border rounded-[var(--radius-md)] text-sm ${
                  organizationType === 'LAB'
                    ? 'border-primary/60 bg-primary-soft text-text-primary'
                    : 'border-border text-text-secondary hover:border-border-strong'
                }`}
              >
                {tAuth('dentalLab')}
              </button>
            </div>
          </div>
          <div className="flex flex-col sm:flex-row sm:justify-end">
            <Button
              type="button"
              variant="primary"
              onClick={handleCreateOrganization}
              isLoading={isLoading}
              disabled={!organizationName.trim() || !organizationEmail.trim()}
              className="w-full sm:w-auto"
            >
              {t('createAndContinue')}
            </Button>
          </div>
        </div>
      )}

      {!organizations.length ? (
        <div className="surface-card p-8 text-center">
          <p className="text-text-secondary">
            {canCreateOrganization ? t('emptyCanCreate') : t('emptyAskOwner')}
          </p>
        </div>
      ) : (
        <div className="grid gap-4">
          {organizations.map((org) => (
            <button
              key={org.id}
              onClick={() => selectOrganization(org.id)}
              className="surface-card p-4 sm:p-6 transition-all text-left flex items-center gap-3 sm:gap-4 hover:border-primary/60 w-full min-w-0"
            >
              <div className="p-2.5 sm:p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary shrink-0">
                {getIcon(org.type)}
              </div>

              <div className="flex-1 min-w-0">
                <h3 className="text-base sm:text-lg font-semibold text-text-primary truncate">
                  {org.name}
                </h3>
                <p className="text-sm text-text-secondary">
                  {getTypeLabel(org.type)}
                </p>
              </div>

              <div className="text-primary text-sm shrink-0 hidden sm:block">
                {t('continueArrow')}
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
