import { db } from "@/lib/db";
import { getOrgContext, canOrgModule } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { btn, Card, EmptyState, Field, PageHeader, StatusBadge, input, label } from "@/components/ui";
import { fmtDate, parseJSON } from "@/lib/utils";
import { DOC_CATEGORIES, DOC_CATEGORY_LABELS, ORG_TYPES, ORG_TYPE_LABELS, INDIAN_STATES } from "@/lib/constants";
import {
  deleteOrgDocument, updateOrgAbout, updateOrgBranding, updateOrgContacts, updateOrgInfo, uploadOrgDocument,
} from "./actions";

export const metadata = { title: "Organization Profile" };

const CONTACT_KINDS: { kind: string; label: string }[] = [
  { kind: "primary", label: "Primary Contact" },
  { kind: "finance", label: "Finance Contact" },
  { kind: "event", label: "Event Contact" },
  { kind: "technical", label: "Technical Contact" },
  { kind: "emergency", label: "Emergency Contact" },
];

function docStatus(expiresAt: Date | null): string {
  if (!expiresAt) return "ACTIVE";
  const days = (expiresAt.getTime() - Date.now()) / 86400_000;
  if (days < 0) return "EXPIRED";
  if (days < 30) return "EXPIRING";
  return "ACTIVE";
}

export default async function OrganizationProfilePage({
  searchParams,
}: {
  searchParams: Promise<{ saved?: string; error?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "organization")) {
    return <EmptyState title="No access" body="Organization profile is managed by owners and admins." />;
  }
  const canEdit = ["OWNER", "ADMIN"].includes(ctx.role);
  const { saved, error } = await searchParams;
  const org = await db.organization.findUniqueOrThrow({
    where: { id: ctx.org.id },
    include: { documents: { orderBy: { createdAt: "desc" } }, _count: { select: { conferences: true, members: true } } },
  });
  const social = parseJSON<Record<string, string>>(org.socialLinks, {});
  const contacts = parseJSON<{ kind: string; name: string; email: string; phone: string }[]>(org.contacts, []);
  const contactFor = (kind: string) => contacts.find((c) => c.kind === kind);

  return (
    <main>
      <PageHeader
        title="🏢 Organization Profile"
        sub="The complete identity of your organization — legal details, branding, contacts and secure documents."
      />
      {saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ Saved.</p>}
      {error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

      {/* Identity header */}
      <Card className="mb-6 overflow-hidden">
        <div className="h-28 w-full" style={{ background: org.coverUrl ? undefined : `linear-gradient(120deg, ${org.brandColor}33, ${org.brandColor}0d)` }}>
          {org.coverUrl && (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={org.coverUrl} alt="" className="h-28 w-full object-cover" />
          )}
        </div>
        <div className="flex flex-wrap items-center gap-4 px-6 pb-5">
          {org.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={org.logoUrl} alt="" className="-mt-7 h-16 w-16 rounded-2xl border-4 border-white bg-white object-contain shadow-lg" />
          ) : (
            <span className="-mt-7 flex h-16 w-16 items-center justify-center rounded-2xl border-4 border-white text-2xl font-bold text-white shadow-lg" style={{ background: org.brandColor }}>
              {org.name[0]}
            </span>
          )}
          <div className="min-w-0 flex-1 pt-2">
            <h2 className="text-lg font-bold text-zinc-100">{org.name}</h2>
            <p className="text-xs text-zinc-500">
              {[org.legalName, org.orgType ? ORG_TYPE_LABELS[org.orgType] : null, org.city, org.foundedYear ? `est. ${org.foundedYear}` : null].filter(Boolean).join(" · ") || "Complete your profile below"}
            </p>
          </div>
          <div className="flex gap-6 pt-2 text-center text-sm">
            <div><div className="font-bold text-zinc-100 tabular-nums">{org._count.conferences}</div><div className="text-[10px] uppercase tracking-wider text-zinc-500">Conferences</div></div>
            <div><div className="font-bold text-zinc-100 tabular-nums">{org._count.members}</div><div className="text-[10px] uppercase tracking-wider text-zinc-500">Team</div></div>
            <div><div className="font-bold text-zinc-100 tabular-nums">{org.documents.length}</div><div className="text-[10px] uppercase tracking-wider text-zinc-500">Documents</div></div>
          </div>
        </div>
      </Card>

      <div className="grid gap-6 xl:grid-cols-2">
        {/* Organization information */}
        <Card className="p-6">
          <h3 className="text-sm font-bold text-zinc-100">Organization Information</h3>
          <p className="mb-4 text-xs text-zinc-500">Legal identity and registration details.</p>
          <form action={updateOrgInfo} className="grid gap-4 sm:grid-cols-2">
            <Field name="name" title="Organization Name *"><input id="name" name="name" defaultValue={org.name} required className={input} disabled={!canEdit} /></Field>
            <Field name="legalName" title="Legal Name"><input id="legalName" name="legalName" defaultValue={org.legalName ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="orgType" title="Organization Type">
              <select id="orgType" name="orgType" defaultValue={org.orgType ?? ""} className={input} disabled={!canEdit}>
                <option value="">— Select —</option>
                {ORG_TYPES.map((t) => <option key={t} value={t}>{ORG_TYPE_LABELS[t]}</option>)}
              </select>
            </Field>
            <Field name="regNumber" title="Registration Number"><input id="regNumber" name="regNumber" defaultValue={org.regNumber ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="industry" title="Industry"><input id="industry" name="industry" defaultValue={org.industry ?? ""} placeholder="Technology, Education…" className={input} disabled={!canEdit} /></Field>
            <Field name="foundedYear" title="Founded Year"><input id="foundedYear" name="foundedYear" type="number" min="1800" max="2100" defaultValue={org.foundedYear ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="website" title="Website"><input id="website" name="website" type="url" defaultValue={org.website ?? ""} placeholder="https://…" className={input} disabled={!canEdit} /></Field>
            <Field name="email" title="Official Email"><input id="email" name="email" type="email" defaultValue={org.email ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="phone" title="Phone"><input id="phone" name="phone" defaultValue={org.phone ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="gstin" title="GST / VAT Number"><input id="gstin" name="gstin" defaultValue={org.gstin ?? ""} className={input} disabled={!canEdit} /></Field>
            <div className="sm:col-span-2"><Field name="address" title="Address"><input id="address" name="address" defaultValue={org.address ?? ""} className={input} disabled={!canEdit} /></Field></div>
            <Field name="city" title="City"><input id="city" name="city" defaultValue={org.city ?? ""} className={input} disabled={!canEdit} /></Field>
            <Field name="state" title="State">
              <select id="state" name="state" defaultValue={org.state ?? ""} className={input} disabled={!canEdit}>
                <option value="">— Select —</option>
                {INDIAN_STATES.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </Field>
            <Field name="country" title="Country"><input id="country" name="country" defaultValue={org.country ?? "India"} className={input} disabled={!canEdit} /></Field>
            <Field name="pincode" title="PIN Code"><input id="pincode" name="pincode" defaultValue={org.pincode ?? ""} className={input} disabled={!canEdit} /></Field>
            {canEdit && <div className="sm:col-span-2"><button className={btn.primary}>Save information</button></div>}
          </form>
        </Card>

        <div className="space-y-6">
          {/* Branding */}
          <Card className="p-6">
            <h3 className="text-sm font-bold text-zinc-100">Branding</h3>
            <p className="mb-4 text-xs text-zinc-500">Logo, cover image, brand color and email signature.</p>
            <form action={updateOrgBranding} className="grid gap-4 sm:grid-cols-2">
              <Field name="logo" title="Organization Logo"><input id="logo" name="logo" type="file" accept="image/*" className={`${input} file:mr-3 file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-3 file:py-1 file:text-xs file:font-semibold file:text-indigo-600`} disabled={!canEdit} /></Field>
              <Field name="cover" title="Cover Image"><input id="cover" name="cover" type="file" accept="image/*" className={`${input} file:mr-3 file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-3 file:py-1 file:text-xs file:font-semibold file:text-indigo-600`} disabled={!canEdit} /></Field>
              <Field name="brandColor" title="Brand Color">
                <div className="flex items-center gap-2">
                  <input id="brandColor" name="brandColor" type="color" defaultValue={org.brandColor} className="h-9 w-14 cursor-pointer rounded-lg border border-white/80 bg-white/70" disabled={!canEdit} />
                  <span className="text-xs text-zinc-500">{org.brandColor}</span>
                </div>
              </Field>
              <div className="sm:col-span-2">
                <Field name="emailSignature" title="Email Signature">
                  <textarea id="emailSignature" name="emailSignature" rows={2} defaultValue={org.emailSignature ?? ""} placeholder="Warm regards, Team…" className={input} disabled={!canEdit} />
                </Field>
              </div>
              {canEdit && <div><button className={btn.primary}>Save branding</button></div>}
            </form>
          </Card>

          {/* About */}
          <Card className="p-6">
            <h3 className="text-sm font-bold text-zinc-100">About Organization</h3>
            <p className="mb-4 text-xs text-zinc-500">Shown on public conference pages and used by communications.</p>
            <form action={updateOrgAbout} className="grid gap-4">
              <Field name="description" title="Description"><textarea id="description" name="description" rows={3} defaultValue={org.description ?? ""} className={input} disabled={!canEdit} /></Field>
              <div className="grid gap-4 sm:grid-cols-2">
                <Field name="mission" title="Mission"><textarea id="mission" name="mission" rows={2} defaultValue={org.mission ?? ""} className={input} disabled={!canEdit} /></Field>
                <Field name="vision" title="Vision"><textarea id="vision" name="vision" rows={2} defaultValue={org.vision ?? ""} className={input} disabled={!canEdit} /></Field>
              </div>
              <Field name="expertise" title="Areas of Expertise (comma-separated)"><input id="expertise" name="expertise" defaultValue={org.expertise ?? ""} placeholder="AI, Developer events, Research…" className={input} disabled={!canEdit} /></Field>
              <Field name="achievements" title="Key Achievements"><textarea id="achievements" name="achievements" rows={2} defaultValue={org.achievements ?? ""} className={input} disabled={!canEdit} /></Field>
              <div className="grid gap-4 sm:grid-cols-2">
                <Field name="linkedin" title="LinkedIn"><input id="linkedin" name="linkedin" defaultValue={social.linkedin ?? ""} className={input} disabled={!canEdit} /></Field>
                <Field name="twitter" title="X / Twitter"><input id="twitter" name="twitter" defaultValue={social.twitter ?? ""} className={input} disabled={!canEdit} /></Field>
                <Field name="youtube" title="YouTube"><input id="youtube" name="youtube" defaultValue={social.youtube ?? ""} className={input} disabled={!canEdit} /></Field>
                <Field name="instagram" title="Instagram"><input id="instagram" name="instagram" defaultValue={social.instagram ?? ""} className={input} disabled={!canEdit} /></Field>
              </div>
              {canEdit && <div><button className={btn.primary}>Save about</button></div>}
            </form>
          </Card>
        </div>
      </div>

      {/* Contacts */}
      <Card className="mt-6 p-6">
        <h3 className="text-sm font-bold text-zinc-100">Contact Information</h3>
        <p className="mb-4 text-xs text-zinc-500">Who to reach for what — used across conferences and communications.</p>
        <form action={updateOrgContacts}>
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {CONTACT_KINDS.map(({ kind, label: l }) => {
              const c = contactFor(kind);
              return (
                <div key={kind} className="rounded-xl border border-white/70 bg-white/40 p-4">
                  <div className={label}>{l}</div>
                  <div className="space-y-2">
                    <input name={`${kind}_name`} defaultValue={c?.name ?? ""} placeholder="Name" className={input} disabled={!canEdit} aria-label={`${l} name`} />
                    <input name={`${kind}_email`} type="email" defaultValue={c?.email ?? ""} placeholder="Email" className={input} disabled={!canEdit} aria-label={`${l} email`} />
                    <input name={`${kind}_phone`} defaultValue={c?.phone ?? ""} placeholder="Phone" className={input} disabled={!canEdit} aria-label={`${l} phone`} />
                  </div>
                </div>
              );
            })}
          </div>
          {canEdit && <button className={`${btn.primary} mt-4`}>Save contacts</button>}
        </form>
      </Card>

      {/* Documents */}
      <Card className="mt-6 p-6">
        <div className="mb-4 flex flex-wrap items-baseline justify-between gap-2">
          <div>
            <h3 className="text-sm font-bold text-zinc-100">Documents</h3>
            <p className="text-xs text-zinc-500">Registration certificates, GST, PAN, agreements, contracts and licenses — with versioning and expiry tracking.</p>
          </div>
        </div>

        {canEdit && (
          <form action={uploadOrgDocument} className="mb-5 grid gap-3 rounded-xl border border-dashed border-indigo-200/80 bg-white/40 p-4 sm:grid-cols-2 lg:grid-cols-5">
            <Field name="file" title="File (PDF, image, doc) *"><input id="file" name="file" type="file" required className={`${input} file:mr-2 file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-2.5 file:py-1 file:text-xs file:font-semibold file:text-indigo-600`} /></Field>
            <Field name="docname" title="Document Name"><input id="docname" name="name" placeholder="GST Certificate 2026" className={input} /></Field>
            <Field name="category" title="Category">
              <select id="category" name="category" className={input}>
                {DOC_CATEGORIES.map((c) => <option key={c} value={c}>{DOC_CATEGORY_LABELS[c]}</option>)}
              </select>
            </Field>
            <Field name="expiresAt" title="Expiry Date"><input id="expiresAt" name="expiresAt" type="date" className={input} /></Field>
            <div className="flex items-end"><button className={`${btn.primary} w-full`}>Upload</button></div>
          </form>
        )}

        {org.documents.length === 0 ? (
          <EmptyState title="No documents yet" body="Upload registration certificates, agreements and licenses to keep them in one secure place." />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[720px] text-sm">
              <thead>
                <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                  <th className="py-2 pr-3">Document</th>
                  <th className="px-3 py-2">Category</th>
                  <th className="px-3 py-2">Version</th>
                  <th className="px-3 py-2">Uploaded</th>
                  <th className="px-3 py-2">Expiry</th>
                  <th className="px-3 py-2">Status</th>
                  <th className="px-3 py-2">Actions</th>
                </tr>
              </thead>
              <tbody>
                {org.documents.map((d) => (
                  <tr key={d.id} className="border-b border-zinc-800/40">
                    <td className="py-2.5 pr-3 font-medium text-zinc-200">📄 {d.name}</td>
                    <td className="px-3 py-2.5 text-zinc-400">{DOC_CATEGORY_LABELS[d.category] ?? d.category}</td>
                    <td className="px-3 py-2.5 tabular-nums text-zinc-400">v{d.version}</td>
                    <td className="whitespace-nowrap px-3 py-2.5 text-xs text-zinc-500">{fmtDate(d.createdAt)}{d.uploadedBy ? ` · ${d.uploadedBy}` : ""}</td>
                    <td className="whitespace-nowrap px-3 py-2.5 text-xs text-zinc-500">{d.expiresAt ? fmtDate(d.expiresAt) : "—"}</td>
                    <td className="px-3 py-2.5"><StatusBadge status={docStatus(d.expiresAt)} /></td>
                    <td className="px-3 py-2.5">
                      <div className="flex items-center gap-2">
                        <a href={d.fileUrl} target="_blank" rel="noreferrer" className={btn.smSecondary}>View</a>
                        {canEdit && (
                          <>
                            <details className="relative">
                              <summary className={`${btn.smSecondary} cursor-pointer select-none [&::-webkit-details-marker]:hidden`}>Replace</summary>
                              <form action={uploadOrgDocument} className="absolute right-0 z-20 mt-1 w-56 space-y-2 rounded-xl border border-white/80 bg-white/95 p-3 shadow-xl">
                                <input type="hidden" name="replaceId" value={d.id} />
                                <input type="hidden" name="name" value={d.name} />
                                <input type="hidden" name="category" value={d.category} />
                                <input name="file" type="file" required className={`${input} text-xs`} aria-label="New version file" />
                                <input name="expiresAt" type="date" className={`${input} text-xs`} aria-label="New expiry date" />
                                <button className={`${btn.sm} w-full`}>Upload v{d.version + 1}</button>
                              </form>
                            </details>
                            <form action={deleteOrgDocument.bind(null, d.id)}>
                              <button className="rounded-lg px-2 py-1.5 text-xs text-red-500 transition hover:bg-red-500/10">Delete</button>
                            </form>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </main>
  );
}
