
import * as ActionIcons from '@/components/Icons';
import { api } from '@/lib/api';
import { Card, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { CheckIcon, ImageIcon, SaveIcon, UserIcon, XIcon } from '@/components/Icons';
import { removePhoto, updateOwnProfile, uploadPhoto } from '../../actions';

type Profile = {
  lawyer: {
    id: number;
    firstName: string;
    lastName: string;
    title: string | null;
    bio: string | null;
    profilePhotoUrl: string | null;
    videoUrl: string | null;
    websiteUrl: string | null;
    phone: string | null;
    email: string | null;
    yearsExperience: number | null;
    acceptsLeads: boolean;
    verificationStatus: string;
  };
  features: string[];
  bioLimit: number;
  firm: { name: string; slug: string } | null;
  city: string | null;
  languageIds: number[];
  allLanguages: { id: number; name: string }[];
  practiceAreas: { name: string; isPrimary: boolean; years: number | null }[];
  completeness: { score: number; checks: { label: string; ok: boolean }[] };
};

export default async function MyProfile({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const d = await api<Profile>('/me/profile');
  const l = d.lawyer;
  const mine = new Set(d.languageIds);
  return (
    <>
      <PageHeader
        title="My profile"
        icon={<UserIcon className="h-5 w-5" />}
        description="What clients see on your public page. Licences, practice areas and verification are checked by our team — add credentials under Credentials."
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid gap-6 xl:grid-cols-[1.6fr_1fr]">
        <Card title="Details" icon={<UserIcon className="h-4 w-4" />}>
          <form action={updateOwnProfile} className="grid gap-4 p-5 text-sm">
            <input type="hidden" name="id" value={l.id} />
            <input type="hidden" name="full" value="1" />
            <input type="hidden" name="back" value="/portal/profile" />
            <div className="grid gap-4 sm:grid-cols-2">
              <label className="block">
                <span className="field-label"><ActionIcons.UserIcon />Name</span>
                <input value={`${l.firstName} ${l.lastName}`} disabled className="field" />
                <span className="mt-1 block text-xs text-muted">Your name comes from the licence register. Report an error from your public page.</span>
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.FileTextIcon />Title</span>
                <input name="title" maxLength={150} defaultValue={l.title ?? ''} placeholder="e.g. Family law partner" className="field" />
              </label>
            </div>
            <label className="block">
              <span className="field-label"><ActionIcons.FileTextIcon />Biography</span>
              <textarea name="bio" rows={8} maxLength={d.bioLimit} defaultValue={l.bio ?? ''} className="field" />
              <span className="mt-1 block text-xs text-muted">
                Up to {d.bioLimit.toLocaleString('en-US')} characters{d.bioLimit < 5000 ? ' (Premium allows 5,000)' : ''}. 150+ characters improves your profile-quality score. Describe your practice factually; avoid promises about outcomes.
              </span>
            </label>
            <div className="grid gap-4 sm:grid-cols-2">
              <label className="block">
                <span className="field-label"><ActionIcons.MailIcon />Public email</span>
                <input name="email" type="email" maxLength={255} defaultValue={l.email ?? ''} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.PhoneIcon />Phone</span>
                <input name="phone" type="tel" maxLength={100} defaultValue={l.phone ?? ''} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.GlobeIcon />Website</span>
                <input name="websiteUrl" inputMode="url" placeholder="https://" defaultValue={l.websiteUrl ?? ''} className="field" />
              </label>
              <label className="block">
                <span className="field-label"><ActionIcons.ScaleIcon />Years in practice</span>
                <input name="yearsExperience" type="number" min={0} max={70} defaultValue={l.yearsExperience ?? ''} className="field" />
              </label>
            </div>
            <label className="block">
              <span className="field-label"><ActionIcons.ImageIcon />Introduction video (YouTube or Vimeo link)</span>
              <input name="videoUrl" inputMode="url" placeholder="https://www.youtube.com/watch?v=…" defaultValue={l.videoUrl ?? ''} disabled={!d.features.includes('profile.video')} className="field" />
              {!d.features.includes('profile.video') && (
                <span className="mt-1 block text-xs text-muted">
                  A Premium feature — <a href="/portal/billing" className="link">see plans</a>.
                </span>
              )}
            </label>
            <fieldset>
              <legend className="field-label">Languages you work in</legend>
              <div className="mt-1 grid max-h-48 grid-cols-2 gap-1.5 overflow-y-auto rounded-lg border border-rule p-3 sm:grid-cols-3">
                {d.allLanguages.map((lang) => (
                  <label key={lang.id} className="flex items-center gap-2 text-sm">
                    <input type="checkbox" name="languageIds" value={lang.id} defaultChecked={mine.has(lang.id)} /> {lang.name}
                  </label>
                ))}
              </div>
            </fieldset>
            <label className="flex items-center gap-2.5 font-medium">
              <input type="checkbox" name="acceptsLeads" defaultChecked={l.acceptsLeads} /> Accept enquiries through Justice Choice
            </label>
            <div className="border-t border-rule pt-4">
              <SubmitButton pendingLabel="Saving…">
                <SaveIcon className="h-4 w-4" /> Save profile
              </SubmitButton>
            </div>
          </form>
        </Card>

        <div className="space-y-6">
          <Card title="Photo" icon={<ImageIcon className="h-4 w-4" />}>
            <div className="space-y-4 p-5 text-sm">
              {l.profilePhotoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={l.profilePhotoUrl} alt="Your profile photo" className="h-32 w-32 rounded-xl border border-rule object-cover" />
              ) : (
                <div className="grid h-32 w-32 place-items-center rounded-xl border border-dashed border-rule-strong text-muted">
                  <ImageIcon className="h-8 w-8" />
                </div>
              )}
              <form action={uploadPhoto} className="space-y-2">
                <input name="file" type="file" required accept="image/jpeg,image/png,image/webp" className="field" />
                <p className="text-xs text-muted">JPG, PNG or WebP, up to 5 MB. A clear, professional headshot.</p>
                <div className="flex gap-2">
                  <SubmitButton pendingLabel="Uploading…"><ActionIcons.UploadIcon />Upload photo</SubmitButton>
                  {l.profilePhotoUrl && (
                    <SubmitButton formAction={removePhoto} formNoValidate className="btn btn-quiet btn-sm" confirm="Remove your photo?">
                      <ActionIcons.TrashIcon />Remove
                    </SubmitButton>
                  )}
                </div>
              </form>
            </div>
          </Card>

          <Card title={`Profile completeness · ${d.completeness.score}%`} icon={<CheckIcon className="h-4 w-4" />}>
            <ul className="divide-y divide-rule text-sm">
              {d.completeness.checks.map((c) => (
                <li key={c.label} className="flex items-center gap-2 px-4 py-2">
                  {c.ok ? <CheckIcon className="h-4 w-4 text-ledger" /> : <XIcon className="h-4 w-4 text-muted" />}
                  <span className={c.ok ? 'text-ink-2' : 'text-ink'}>{c.label}</span>
                </li>
              ))}
            </ul>
            <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Profile quality is 5% of the ranking. It measures completeness, never payment.</p>
          </Card>

          <Card title="Practice areas">
            {d.practiceAreas.length ? (
              <ul className="flex flex-wrap gap-2 p-4">
                {d.practiceAreas.map((p) => (
                  <li key={p.name}>
                    <Pill value={`${p.name}${p.years ? ` · ${p.years} yrs` : ''}`} tone={p.isPrimary ? 'good' : 'muted'} />
                  </li>
                ))}
              </ul>
            ) : (
              <p className="p-4 text-sm text-muted">None on file.</p>
            )}
            <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">
              {d.firm ? `${d.firm.name} · ` : ''}
              {d.city ?? ''} — practice areas are maintained by our data team.
            </p>
          </Card>
        </div>
      </div>
    </>
  );
}
