"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost, apiPut } from "@/lib/api";
import { PageHeader } from "@/components/ui/page-header";
import { NotificationDeliveryPanel } from "@/components/notifications/notification-delivery-panel";
import { NotificationEmailDigestPanel } from "@/components/notifications/notification-email-digest-panel";
import { NotificationPreferencePanel } from "@/components/notifications/notification-preference-panel";
import type { AppNotificationSnapshot, NotificationDeliveryReadiness, NotificationPreferences, Organization, User } from "@/types";

type SettingsTab = "profile" | "team" | "notifications" | "access";

function formatDate(value?: string | null) {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
}

function userName(user: User) {
  return [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email || "Unnamed user";
}

const SETTINGS_TABS: Array<{ key: SettingsTab; label: string; helper: string }> = [
  { key: "profile", label: "Profile", helper: "Company name and workspace link" },
  { key: "team", label: "Team", helper: "Users, roles, and access" },
  { key: "notifications", label: "Notifications", helper: "Alert preferences and opt-ins" },
  { key: "access", label: "Access & setup", helper: "Security and integrations links" },
];

export default function CompanyPage() {
  const [activeTab, setActiveTab] = useState<SettingsTab>("profile");
  const [organization, setOrganization] = useState<Organization | null>(null);
  const [users, setUsers] = useState<User[]>([]);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [notificationPreferences, setNotificationPreferences] = useState<NotificationPreferences | null>(null);
  const [notificationReadiness, setNotificationReadiness] = useState<NotificationDeliveryReadiness | null>(null);
  const [notificationSnapshot, setNotificationSnapshot] = useState<AppNotificationSnapshot | null>(null);
  const [savingCompany, setSavingCompany] = useState(false);
  const [savingUser, setSavingUser] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [companyForm, setCompanyForm] = useState({ name: "", slug: "" });
  const [userForm, setUserForm] = useState({ firstName: "", lastName: "", email: "", password: "", role: "DISPATCHER" });
  const [loaded, setLoaded] = useState(false);

  const isAdmin = currentUser?.role === "ORG_ADMIN";

  async function loadAll() {
    try {
      setError(null);
      const meData = await apiGet<{ user: User }>("/api/auth/me");
      setCurrentUser(meData.user);

      if (meData.user.role !== "ORG_ADMIN") {
        setLoaded(true);
        return;
      }

      const [orgData, usersData, notificationData] = await Promise.all([
        apiGet<{ organization: Organization }>("/api/organization"),
        apiGet<{ users: User[] }>("/api/users"),
        apiGet<{ snapshot: AppNotificationSnapshot }>("/api/app-notifications"),
      ]);
      setOrganization(orgData.organization);
      setCompanyForm({ name: orgData.organization.name, slug: orgData.organization.slug });
      setUsers(usersData.users);
      setNotificationPreferences(notificationData.snapshot.preferences);
      setNotificationReadiness(notificationData.snapshot.deliveryReadiness);
      setNotificationSnapshot(notificationData.snapshot);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load workspace settings");
    } finally {
      setLoaded(true);
    }
  }

  useEffect(() => {
    loadAll();
  }, []);

  async function saveCompany(e: React.FormEvent) {
    e.preventDefault();
    try {
      setSavingCompany(true);
      setError(null);
      const data = await apiPut<{ organization: Organization }>("/api/organization", companyForm);
      setOrganization(data.organization);
      setCompanyForm({ name: data.organization.name, slug: data.organization.slug });
    } catch (err: any) {
      setError(err?.message ?? "Failed to save workspace profile");
    } finally {
      setSavingCompany(false);
    }
  }

  async function createUser(e: React.FormEvent) {
    e.preventDefault();
    try {
      setSavingUser(true);
      setError(null);
      await apiPost("/api/users", userForm);
      setUserForm({ firstName: "", lastName: "", email: "", password: "", role: "DISPATCHER" });
      await loadAll();
      setActiveTab("team");
    } catch (err: any) {
      setError(err?.message ?? "Failed to add team member");
    } finally {
      setSavingUser(false);
    }
  }

  async function toggleUser(user: User) {
    try {
      setError(null);
      const path = user.isActive ? `/api/users/${user.id}/deactivate` : `/api/users/${user.id}/reactivate`;
      await apiPost(path, {});
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? "Failed to update team member");
    }
  }

  const stats = useMemo(() => ([
    { label: "Active users", value: String(users.filter((u) => u.isActive).length), helpText: "People who can currently work in this workspace." },
    { label: "Pending verification", value: String(users.filter((u) => u.isActive && !u.emailVerifiedAt).length), helpText: "Team members who still need to verify email." },
    { label: "Admin seats", value: String(users.filter((u) => u.role === "ORG_ADMIN" && u.isActive).length), helpText: "Company admins who can manage settings." },
    { label: "Load records", value: organization?._count?.loads ? String(organization._count.loads) : "0", helpText: "Load records tied to this workspace." },
  ]), [users, organization]);

  if (!loaded) {
    return <div className="text-sm text-gray-500">Loading workspace access...</div>;
  }

  if (!isAdmin) {
    return (
      <div className="space-y-6">
        <PageHeader
          title="Workspace Settings"
          subtitle="Workspace settings are only for company admins. Dispatchers stay focused on daily dispatch work."
        />
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-6 text-sm text-amber-900">
          <div className="text-base font-semibold">Admin access required</div>
          <p className="mt-2">Only company admins can manage the company profile, team access, and workspace setup.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Workspace Settings"
        subtitle="Manage the company profile, team access, and notification settings. Provider setup lives in Third-Party Integrations."
        action={
          <Link href="/company/integrations" className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium">
            Open Integrations
          </Link>
        }
      />

      {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Clean settings</div>
            <h2 className="mt-1 text-lg font-semibold text-slate-900">Choose one settings area</h2>
            <p className="mt-1 text-sm leading-6 text-slate-600">This page only keeps company profile and team access. Email, Twilio, maps, QuickBooks, Stripe, and other API setup stay in Integrations.</p>
          </div>
          <div className="rounded-2xl border border-sky-100 bg-sky-50 p-4 text-sm leading-6 text-sky-800">
            Setup rule: daily work pages stay simple. Technical setup belongs in settings.
          </div>
        </div>

        <div className="mt-5 flex gap-2 overflow-x-auto pb-2">
          {SETTINGS_TABS.map((tab) => (
            <button
              key={tab.key}
              type="button"
              onClick={() => setActiveTab(tab.key)}
              className={`min-w-fit rounded-2xl px-4 py-3 text-left text-sm font-semibold transition ${activeTab === tab.key ? "bg-slate-950 text-white" : "border border-slate-200 bg-white text-slate-700 hover:bg-slate-50"}`}
            >
              <div>{tab.label}</div>
              <div className={`mt-1 text-[11px] font-normal ${activeTab === tab.key ? "text-slate-200" : "text-slate-500"}`}>{tab.helper}</div>
            </button>
          ))}
        </div>
      </section>

      <section className="grid gap-4 lg:grid-cols-4">
        {stats.map((item) => (
          <div key={item.label} className="rounded-2xl border bg-white p-5 shadow-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{item.label}</div>
            <div className="mt-2 text-2xl font-semibold text-slate-950">{item.value}</div>
            <p className="mt-2 text-xs leading-5 text-slate-500">{item.helpText}</p>
          </div>
        ))}
      </section>

      {activeTab === "profile" ? (
        <section id="workspace-profile" className="rounded-2xl border bg-white p-6 shadow-sm">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <h2 className="text-lg font-semibold">Workspace profile</h2>
              <p className="mt-1 text-sm text-gray-500">Keep the company name and workspace link clean.</p>
            </div>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">Company identity</span>
          </div>

          <form onSubmit={saveCompany} className="mt-6 space-y-4">
            <label className="block text-sm">
              <div className="mb-1 font-medium">Company name</div>
              <input value={companyForm.name} onChange={(e) => setCompanyForm((p) => ({ ...p, name: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium">Company slug</div>
              <input value={companyForm.slug} onChange={(e) => setCompanyForm((p) => ({ ...p, slug: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
            <div className="grid gap-3 sm:grid-cols-2 text-sm text-gray-600">
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Created</div><div className="mt-1">{formatDate(organization?.createdAt)}</div></div>
              <div className="rounded-xl border bg-gray-50 p-3"><div className="font-medium text-gray-900">Updated</div><div className="mt-1">{formatDate(organization?.updatedAt)}</div></div>
            </div>
            <button type="submit" disabled={savingCompany} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{savingCompany ? "Saving..." : "Save workspace profile"}</button>
          </form>
        </section>
      ) : null}

      {activeTab === "team" ? (
        <div className="space-y-6">
          <section id="team-access" className="rounded-2xl border bg-white p-6 shadow-sm">
            <h2 className="text-lg font-semibold">Add team member</h2>
            <p className="mt-1 text-sm text-gray-500">Add dispatchers and additional company admins inside this workspace.</p>

            <form onSubmit={createUser} className="mt-6 space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="block text-sm">
                  <div className="mb-1 font-medium">First name</div>
                  <input value={userForm.firstName} onChange={(e) => setUserForm((p) => ({ ...p, firstName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
                </label>
                <label className="block text-sm">
                  <div className="mb-1 font-medium">Last name</div>
                  <input value={userForm.lastName} onChange={(e) => setUserForm((p) => ({ ...p, lastName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
                </label>
              </div>
              <label className="block text-sm">
                <div className="mb-1 font-medium">Email</div>
                <input type="email" value={userForm.email} onChange={(e) => setUserForm((p) => ({ ...p, email: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
              </label>
              <div className="grid gap-4 sm:grid-cols-[1fr_180px]">
                <label className="block text-sm">
                  <div className="mb-1 font-medium">Temporary password</div>
                  <input type="password" value={userForm.password} onChange={(e) => setUserForm((p) => ({ ...p, password: e.target.value }))} className="w-full rounded-xl border px-3 py-2" />
                </label>
                <label className="block text-sm">
                  <div className="mb-1 font-medium">Role</div>
                  <select value={userForm.role} onChange={(e) => setUserForm((p) => ({ ...p, role: e.target.value }))} className="w-full rounded-xl border px-3 py-2">
                    <option value="DISPATCHER">Dispatcher</option>
                    <option value="ORG_ADMIN">Company Admin</option>
                  </select>
                </label>
              </div>
              <button type="submit" disabled={savingUser} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60">{savingUser ? "Adding..." : "Add team member"}</button>
            </form>
          </section>

          <section id="workspace-users" className="rounded-2xl border bg-white p-6 shadow-sm">
            <h2 className="text-lg font-semibold">Workspace users</h2>
            <p className="mt-1 text-sm text-gray-500">Keep this roster clean. Remove access when someone no longer works in the workspace.</p>

            <div className="mt-6 overflow-hidden rounded-2xl border">
              <table className="min-w-full divide-y divide-gray-200 text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Name</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Email</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Role</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Status</th>
                    <th className="px-4 py-3 text-left font-medium text-gray-600">Last login</th>
                    <th className="px-4 py-3 text-right font-medium text-gray-600">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100 bg-white">
                  {users.map((user) => {
                    const isSelf = user.id === currentUser?.id;
                    return (
                      <tr key={user.id}>
                        <td className="px-4 py-3 font-medium">{userName(user)}</td>
                        <td className="px-4 py-3">{user.email}</td>
                        <td className="px-4 py-3">{user.role === "ORG_ADMIN" ? "Company Admin" : "Dispatcher"}</td>
                        <td className="px-4 py-3">{user.isActive ? "Active" : "Inactive"}</td>
                        <td className="px-4 py-3">{formatDate(user.lastLoginAt)}</td>
                        <td className="px-4 py-3 text-right">
                          {!isSelf ? (
                            <button onClick={() => toggleUser(user)} className="rounded-lg border px-3 py-1.5 text-xs font-medium">
                              {user.isActive ? "Deactivate" : "Reactivate"}
                            </button>
                          ) : (
                            <span className="text-xs text-gray-400">Current session</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </section>
        </div>
      ) : null}


      {activeTab === "notifications" ? (
        <div className="space-y-6">
          <section className="rounded-2xl border bg-white p-6 shadow-sm">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
              <div>
                <h2 className="text-lg font-semibold">Notification Settings</h2>
                <p className="mt-1 text-sm leading-6 text-gray-500">Manage alert preferences, email choices, and urgent text opt-in here. The user-facing Notifications page stays focused on alert review only.</p>
              </div>
              <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">Settings area</span>
            </div>
          </section>

          {notificationReadiness ? <NotificationDeliveryPanel readiness={notificationReadiness} /> : null}
          {notificationSnapshot ? <NotificationEmailDigestPanel snapshot={notificationSnapshot} /> : null}
          {notificationPreferences ? (
            <NotificationPreferencePanel initialPreferences={notificationPreferences} />
          ) : (
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-5 text-sm text-slate-600">Loading notification settings...</div>
          )}
        </div>
      ) : null}

      {activeTab === "access" ? (
        <section className="rounded-2xl border bg-white p-6 shadow-sm">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <h2 className="text-lg font-semibold">Access & setup</h2>
              <p className="mt-1 text-sm text-gray-500">Use these clear setup areas instead of placing technical settings on daily work pages.</p>
            </div>
            <span className="rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">Clean setup path</span>
          </div>

          <div className="mt-6 grid gap-4 lg:grid-cols-4">
            <Link href="/profile" className="rounded-2xl border bg-slate-50 p-5 transition hover:bg-white hover:shadow-sm">
              <div className="font-semibold text-slate-900">Profile & security</div>
              <p className="mt-2 text-sm leading-6 text-slate-600">Manage password and account security.</p>
            </Link>
            <button type="button" onClick={() => setActiveTab("notifications")} className="rounded-2xl border bg-slate-50 p-5 text-left transition hover:bg-white hover:shadow-sm">
              <div className="font-semibold text-slate-900">Notification Settings</div>
              <p className="mt-2 text-sm leading-6 text-slate-600">Alert choices, email preferences, and urgent text opt-in.</p>
            </button>
            <Link href="/company/integrations" className="rounded-2xl border bg-slate-50 p-5 transition hover:bg-white hover:shadow-sm">
              <div className="font-semibold text-slate-900">Third-Party Integrations</div>
              <p className="mt-2 text-sm leading-6 text-slate-600">Email, Twilio, Google Maps, QuickBooks, Stripe, and future API setup.</p>
            </Link>
            <Link href="/billing" className="rounded-2xl border bg-slate-50 p-5 transition hover:bg-white hover:shadow-sm">
              <div className="font-semibold text-slate-900">Billing records</div>
              <p className="mt-2 text-sm leading-6 text-slate-600">Review invoices, payments, and open balances without mixing billing setup into this page.</p>
            </Link>
          </div>
        </section>
      ) : null}
    </div>
  );
}
