'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

import { getActiveBusinessSession, getBusinessAccessToken, nameFromEmail } from '@/lib/business-session';
import { getBusinessProfile, type BusinessProfile } from '@/services/employee-login/employee-login.client';
import { toast } from '@/lib/toast';
import { describeApiError, isSessionExpired, toastApiError } from '@/lib/api-error';

function fullName(profile: BusinessProfile): string {
  return [profile.firstName, profile.middleName, profile.lastName].filter(Boolean).join(' ');
}

function formatDate(value: string | null): string {
  if (!value) return '—';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}

function titleCaseWords(value: string | null): string {
  if (!value) return '—';
  return value
    .toLowerCase()
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

interface FieldProps {
  label: string;
  value: string;
}

function Field({ label, value }: FieldProps) {
  return (
    <div>
      <div className="text-xs font-medium text-[var(--fra-muted)]">{label}</div>
      <div className="mt-0.5 text-sm font-semibold text-[var(--fra-heading)]">{value}</div>
    </div>
  );
}

interface SectionProps {
  title: string;
  children: React.ReactNode;
}

function Section({ title, children }: SectionProps) {
  return (
    <div className="border-b border-dashed border-[var(--fra-border)] py-5 first:pt-0 last:border-b-0 last:pb-0">
      <h3 className="mb-4 text-[15px] font-bold text-[var(--fra-heading)]">{title}</h3>
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">{children}</div>
    </div>
  );
}

export default function EmployeeProfileView() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [email, setEmail] = useState<string | null>(null);
  const [role, setRole] = useState<string | null>(null);
  const [profile, setProfile] = useState<BusinessProfile | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function load() {
      const session = getActiveBusinessSession();
      if (!session) {
        router.replace('/employee-login');
        return;
      }
      setEmail(session.email);
      setRole(session.role);

      const token = getBusinessAccessToken();
      const res = token ? await getBusinessProfile(token) : null;
      if (cancelled) return;

      if (!res?.success) {
        // Only a SESSION problem means sign in again. This used to redirect on
        // any failure at all, so a dropped connection or a 500 looked exactly
        // like being logged out — the employee landed on sign-in, signed in
        // fine, and came straight back to the same broken page.
        if (!res || isSessionExpired(res)) {
          toastApiError(res, {
            fallback: 'Your session has expired. Please sign in again.',
            id: 'employee-profile',
          });
          router.replace(`/employee-login?next=${encodeURIComponent('/employee-profile')}`);
          return;
        }
        const message = describeApiError(res, 'We could not load your profile.');
        setError(message);
        toast.error(message, { id: 'employee-profile' });
        setLoading(false);
        return;
      }
      if (!res.data) {
        setError('No traveler profile on file yet.');
      } else {
        setProfile(res.data);
      }
      setLoading(false);
    }

    load();
    return () => {
      cancelled = true;
    };
  }, [router]);

  if (loading) {
    return <div className="py-10 text-center text-sm text-[var(--fra-muted)]">Loading your profile…</div>;
  }

  const displayName = profile ? fullName(profile) || nameFromEmail(email ?? '') : nameFromEmail(email ?? '');

  return (
    <div>
      <div className="mb-6 flex items-center gap-4">
        <span className="flex size-14 shrink-0 items-center justify-center rounded-full bg-[var(--fra-navy-2)] text-lg font-bold text-white">
          {displayName
            .trim()
            .split(/\s+/)
            .slice(0, 2)
            .map((p) => p.charAt(0).toUpperCase())
            .join('')}
        </span>
        <div className="min-w-0">
          <h2 className="truncate text-[22px] font-extrabold text-[var(--fra-heading)]">{displayName}</h2>
          <p className="truncate text-sm text-[var(--fra-muted)]">
            {email}
            {role && <span className="ml-2 rounded-full bg-[var(--fra-blue-bg)] px-2 py-0.5 text-xs font-semibold text-[var(--fra-navy-2)]">{role}</span>}
          </p>
        </div>
      </div>

      {error && (
        <p className="mb-5 rounded-[10px] bg-[var(--fra-pending-bg)] px-3.5 py-3 text-sm text-[var(--fra-pending)]">
          {error}
        </p>
      )}

      {profile && (
        <>
          <Section title="Work details">
            <Field label="Employee ID" value={profile.employeeId ?? '—'} />
            <Field label="Department" value={profile.department ?? '—'} />
            <Field label="Office location" value={profile.officeLocation ?? '—'} />
          </Section>

          <Section title="Personal details (as per passport)">
            <Field label="Full name" value={fullName(profile) || '—'} />
            <Field label="Gender" value={titleCaseWords(profile.gender)} />
            <Field label="Date of birth" value={formatDate(profile.dateOfBirth)} />
            <Field label="Nationality" value={profile.nationality ?? '—'} />
            <Field label="Passport number" value={profile.passportNumber ?? '—'} />
            <Field label="Passport expiry" value={formatDate(profile.passportExpiry)} />
            <Field label="Issuing country" value={profile.passportIssuingCountry ?? '—'} />
          </Section>

          <Section title="Contact">
            <Field
              label="Mobile number"
              value={profile.mobileNumber ? `${profile.mobileCountryCode ?? ''} ${profile.mobileNumber}` : '—'}
            />
          </Section>
        </>
      )}
    </div>
  );
}
