'use client';

import { Suspense, useEffect, useMemo, useState } from 'react';
import { Link, useRouter } from '@/i18n/navigation';
import { useSearchParams } from 'next/navigation';
import { useForm, type FieldErrors, type UseFormRegister, type UseFormSetValue } from 'react-hook-form';
import type { OrganizationDetailsFormValues } from '@/components/ui/auth/OrganizationDetailsFields';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Lock, Mail, User } from 'lucide-react';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
import { organizationApi } from '@/lib/api/organization';

const acceptOrganizationInviteSchema = z
  .object({
    ownerName: z.string().min(2, 'Name must be at least 2 characters'),
    password: z
      .string()
      .min(8, 'Password must be at least 8 characters')
      .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
      .regex(/[0-9]/, 'Password must contain at least one number'),
    confirmPassword: z.string(),
    organizationName: z.string().min(2, 'Organization name must be at least 2 characters'),
    organizationEmail: z.string().email('Please enter a valid organization email'),
    organizationType: z.enum(['CLINIC', 'LAB'], {
      message: 'Please select organization type',
    }),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ['confirmPassword'],
  });

type AcceptOrganizationInviteForm = z.infer<typeof acceptOrganizationInviteSchema>;

function AcceptOrganizationInviteContent() {
  const params = useSearchParams();
  const router = useRouter();
  const token = useMemo(() => params.get('token') || '', [params]);

  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [inviteInfo, setInviteInfo] = useState<{
    ownerEmail: string;
    organizationName: string;
    organizationType: 'CLINIC' | 'LAB';
    organizationEmail?: string;
    inviterOrganizationName: string;
    expiresAt: string;
    status: 'PENDING' | 'ACCEPTED';
  } | null>(null);

  const {
    register,
    handleSubmit,
    watch,
    trigger,
    setValue,
    reset,
    formState: { errors },
  } = useForm<AcceptOrganizationInviteForm>({
    resolver: zodResolver(acceptOrganizationInviteSchema),
    mode: 'onChange',
    defaultValues: {
      organizationType: undefined,
    },
  });

  const organizationType = watch('organizationType');

  useEffect(() => {
    if (!token) {
      setLoading(false);
      setError('Invalid invitation link');
      return;
    }

    void (async () => {
      setLoading(true);
      setError('');
      try {
        const res = await organizationApi.previewInvite(token);
        setInviteInfo(res.data);
        reset({
          ownerName: '',
          password: '',
          confirmPassword: '',
          organizationName: res.data.organizationName || '',
          organizationEmail: res.data.organizationEmail || '',
          organizationType: res.data.organizationType,
        });
        if (res.data.status === 'ACCEPTED') {
          setSuccess('This invitation is already accepted. You can log in now.');
        }
      } catch (e: unknown) {
        const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
        setError(message || 'Could not load invitation');
      } finally {
        setLoading(false);
      }
    })();
  }, [token, reset]);

  const handleNext = async () => {
    const isValid = await trigger(['ownerName', 'password', 'confirmPassword']);
    if (isValid) {
      setStep(2);
      setError('');
    }
  };

  const onSubmit = async (data: AcceptOrganizationInviteForm) => {
    if (!token) return;
    setError('');
    setSuccess('');
    setSubmitting(true);
    try {
      await organizationApi.acceptInvite({
        token,
        ownerName: data.ownerName.trim(),
        password: data.password,
        organizationName: data.organizationName.trim(),
        organizationEmail: data.organizationEmail.trim(),
        organizationType: data.organizationType,
      });
      setSuccess('Invitation accepted. Redirecting to login...');
      setTimeout(() => router.replace('/login'), 1000);
    } catch (e: unknown) {
      const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
      setError(message || 'Could not accept invitation');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <Link href="/" className="flex justify-center">
          <span className="text-3xl font-semibold text-text-primary">DyoLink</span>
        </Link>
        <h2 className="mt-6 text-center text-2xl font-semibold text-text-primary">
          Accept organization invitation
        </h2>
        <p className="mt-2 text-center text-sm text-text-secondary">
          Already have an account?{' '}
          <Link href="/login" className="font-medium text-primary hover:opacity-90">
            Sign in
          </Link>
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="surface-card py-8 px-4 sm:px-10">
          {loading ? (
            <p className="text-sm text-text-secondary">Loading invitation...</p>
          ) : (
            <>
              {inviteInfo && (
                <div className="mb-6 rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/70 px-3 py-2 text-sm text-text-secondary space-y-1">
                  <p>
                    Invited by:{' '}
                    <span className="text-text-primary">{inviteInfo.inviterOrganizationName}</span>
                  </p>
                </div>
              )}

              {inviteInfo?.status !== 'ACCEPTED' && (
                <RegistrationProgressSteps step={step} />
              )}

              {error && (
                <div className="mb-4 p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
                  <p className="text-sm text-red-600">{error}</p>
                </div>
              )}
              {success && (
                <div className="mb-4 rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-3 py-2 text-sm text-text-primary">
                  {success}
                </div>
              )}

              {inviteInfo?.status !== 'ACCEPTED' && (
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                  {step === 1 && (
                    <>
                      <Input
                        label="Owner email"
                        value={inviteInfo?.ownerEmail ?? ''}
                        readOnly
                        disabled
                        icon={<Mail className="h-5 w-5 icon-flat" />}
                      />
                      <Input
                        label="Full name"
                        {...register('ownerName')}
                        placeholder="John Doe"
                        error={errors.ownerName?.message}
                        icon={<User className="h-5 w-5 icon-flat" />}
                      />
                      <Input
                        label="Password"
                        {...register('password')}
                        type="password"
                        placeholder="••••••••"
                        error={errors.password?.message}
                        icon={<Lock className="h-5 w-5 icon-flat" />}
                      />
                      <Input
                        label="Confirm password"
                        {...register('confirmPassword')}
                        type="password"
                        placeholder="••••••••"
                        error={errors.confirmPassword?.message}
                        icon={<Lock className="h-5 w-5 icon-flat" />}
                      />
                      <Button type="button" variant="primary" onClick={() => void handleNext()} fullWidth>
                        Continue
                      </Button>
                    </>
                  )}

                  {step === 2 && (
                    <>
                      <OrganizationDetailsFields
                        register={register as unknown as UseFormRegister<OrganizationDetailsFormValues>}
                        errors={errors as FieldErrors<OrganizationDetailsFormValues>}
                        organizationType={organizationType}
                        setValue={setValue as unknown as UseFormSetValue<OrganizationDetailsFormValues>}
                      />
                      <div className="flex gap-3">
                        <Button type="button" variant="outline" onClick={() => setStep(1)}>
                          Back
                        </Button>
                        <Button type="submit" variant="primary" isLoading={submitting} fullWidth>
                          Activate organization
                        </Button>
                      </div>
                    </>
                  )}
                </form>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default function AcceptOrganizationInvitePage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen app-web-bg flex items-center justify-center">
          <p className="text-sm text-text-secondary">Loading invitation...</p>
        </div>
      }
    >
      <AcceptOrganizationInviteContent />
    </Suspense>
  );
}
