"use client";

import { useState, type FormEvent } from "react";
import { Pencil } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Field } from "@/components/shared/field";
import { DetailList, Panel, PreviewNotice } from "@/components/shared/page";
import { usePreviewRole } from "@/components/layout/preview-context";
import { useDashboardAuth } from "@/components/layout/dashboard-auth-context";
import { PasswordField } from "@/features/auth/password-field";
import { passwordFieldErrors } from "@/features/auth/model";
import { postAuthRequest } from "@/features/auth/auth-client";
import {
  initials,
  connectedProfileDisplay,
  profileAddressError,
  profileFixture,
  profileInformationError,
  type ProfileAddress,
  type ProfileInformation,
} from "./model";
import {
  passwordChangeFeedback,
  passwordChangeErrors,
  passwordChangePolicyHint,
  passwordChangePayload,
  type PasswordChangeErrors,
} from "./password-change";
export function ProfilePreview() {
  const role = usePreviewRole();
  const { apiConfigured, profile } = useDashboardAuth();
  const connectedProfile = apiConfigured ? connectedProfileDisplay(profile) : null;
  const [information, setInformation] = useState({
    ...profileFixture.information,
  });
  const [address, setAddress] = useState({
    ...profileFixture.address,
  });
  const [draftInfo, setDraftInfo] = useState({
    ...information,
  });
  const [draftAddress, setDraftAddress] = useState({
    ...address,
  });
  const [editing, setEditing] = useState<"information" | "address" | null>(
    null,
  );
  const [error, setError] = useState("");
  const [feedback, setFeedback] = useState("");
  const displayedInformation = apiConfigured
    ? connectedProfile?.information
    : information;
  const displayedAddress = apiConfigured
    ? connectedProfile?.address
    : address;
  const displayedOrganization = apiConfigured
    ? connectedProfile?.organization ?? ""
    : profileFixture.organization;
  function edit(section: "information" | "address") {
    setDraftInfo({
      ...information,
    });
    setDraftAddress({
      ...address,
    });
    setError("");
    setEditing(section);
  }
  function save(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const error =
      editing === "information"
        ? profileInformationError(draftInfo)
        : profileAddressError(draftAddress);
    setError(error ?? "");
    if (error) return;
    if (editing === "information")
      setInformation({
        ...draftInfo,
        email: draftInfo.email.trim().toLowerCase(),
      });
    else
      setAddress({
        ...draftAddress,
      });
    setEditing(null);
    setFeedback(
      "Profile changes applied to this page only. No account or address was updated.",
    );
  }
  function updateInfo(key: keyof ProfileInformation, value: string) {
    setDraftInfo({
      ...draftInfo,
      [key]: value,
    });
  }
  function updateAddress(key: keyof ProfileAddress, value: string) {
    setDraftAddress({
      ...draftAddress,
      [key]: value,
    });
  }
  return (
    <div className="space-y-6">
      {(!displayedInformation || !displayedAddress) ? (
        <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          We couldn’t load supported profile details from your account. Please refresh or contact your administrator.
        </p>
      ) : (
        <>
          <Panel>
            <div className="flex flex-wrap items-center gap-5 p-6">
              <div className="flex size-20 items-center justify-center rounded-full bg-primary/10 text-2xl font-semibold text-primary">
                {initials(displayedInformation.firstName, displayedInformation.lastName)}
              </div>
              <div className="flex-1">
                <h2 className="text-xl font-semibold">
                  {displayedInformation.firstName} {displayedInformation.lastName}
                </h2>
                <p className="mt-2 text-sm text-muted-foreground">
                  <span className="capitalize">{role.replaceAll("-", " ")}</span>
                  {displayedOrganization ? ` · ${displayedOrganization}` : ""}
                </p>
                {(displayedAddress.city || displayedAddress.country) && (
                  <p className="mt-1 text-sm text-muted-foreground">
                    {[displayedAddress.city, displayedAddress.country].filter(Boolean).join(", ")}
                  </p>
                )}
              </div>
              {!apiConfigured && (
                <Button variant="outline" onClick={() => edit("information")}>
                  <Pencil size={15} />
                  Edit Profile
                </Button>
              )}
            </div>
          </Panel>
          <Panel title="Personal Information">
            {!apiConfigured && (
              <div className="flex justify-end px-5 pt-4">
                <Button variant="outline" size="sm" onClick={() => edit("information")}>
                  <Pencil size={15} />
                  Edit Information
                </Button>
              </div>
            )}
            <DetailList
              items={{
                "First Name": displayedInformation.firstName,
                "Last Name": displayedInformation.lastName,
                "Email Address": displayedInformation.email,
                Phone: displayedInformation.phone,
              }}
            />
          </Panel>
          <Panel title="Address">
            {!apiConfigured && (
              <div className="flex justify-end px-5 pt-4">
                <Button variant="outline" size="sm" onClick={() => edit("address")}>
                  <Pencil size={15} />
                  Edit Address
                </Button>
              </div>
            )}
            <DetailList
              items={{
                Country: displayedAddress.country,
                City: displayedAddress.city,
                "State / Province": displayedAddress.state,
                "Postal Code": displayedAddress.postalCode,
              }}
            />
          </Panel>
        </>
      )}
      <PasswordChangePreview apiConfigured={apiConfigured} />
      {!apiConfigured && feedback && <PreviewNotice>{feedback}</PreviewNotice>}
      {!apiConfigured && (
        <Dialog
          open={editing !== null}
          onOpenChange={(open) => {
            if (!open) setEditing(null);
          }}
        >
          <DialogContent>
            <DialogTitle>
              {editing === "address"
                ? "Edit Address"
                : "Edit Personal Information"}
            </DialogTitle>
            <DialogDescription>
              Changes apply to the local sample profile. Use demonstration data.
            </DialogDescription>
            <form onSubmit={save} noValidate className="space-y-5">
              <div className="grid gap-5 sm:grid-cols-2">
                {editing === "information" ? (
                  <>
                    <Field
                      label="First Name"
                      value={draftInfo.firstName}
                      onChange={(e) => updateInfo("firstName", e.target.value)}
                      required
                    />
                    <Field
                      label="Last Name"
                      value={draftInfo.lastName}
                      onChange={(e) => updateInfo("lastName", e.target.value)}
                      required
                    />
                    <Field
                      label="Email Address"
                      type="email"
                      value={draftInfo.email}
                      onChange={(e) => updateInfo("email", e.target.value)}
                      required
                    />
                    <Field
                      label="Phone"
                      type="tel"
                      value={draftInfo.phone}
                      onChange={(e) => updateInfo("phone", e.target.value)}
                      required
                    />
                  </>
                ) : (
                  <>
                    <Field
                      label="Country"
                      value={draftAddress.country}
                      onChange={(e) => updateAddress("country", e.target.value)}
                      required
                    />
                    <Field
                      label="City"
                      value={draftAddress.city}
                      onChange={(e) => updateAddress("city", e.target.value)}
                      required
                    />
                    <Field
                      label="State / Province"
                      value={draftAddress.state}
                      onChange={(e) => updateAddress("state", e.target.value)}
                      required
                    />
                    <Field
                      label="Postal Code"
                      value={draftAddress.postalCode}
                      onChange={(e) => updateAddress("postalCode", e.target.value)}
                      required
                    />
                  </>
                )}
              </div>
              {error && (
                <p role="alert" className="text-sm text-destructive">
                  {error}
                </p>
              )}
              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setEditing(null)}
                >
                  Cancel
                </Button>
                <Button type="submit">Save preview changes</Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
function PasswordChangePreview({ apiConfigured }: { apiConfigured: boolean }) {
  const [current, setCurrent] = useState("");
  const [password, setPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");
  const [fieldErrors, setFieldErrors] = useState<PasswordChangeErrors>({});
  const [formError, setFormError] = useState("");
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSaved(false);

    const nextFieldErrors: PasswordChangeErrors = apiConfigured
      ? passwordChangeErrors(current, password, confirmation)
      : passwordFieldErrors(password, confirmation);
    setFieldErrors(nextFieldErrors);
    setFormError("");
    if (Object.values(nextFieldErrors).some(Boolean)) return;

    if (!apiConfigured) {
      setCurrent("");
      setPassword("");
      setConfirmation("");
      setSaved(true);
      return;
    }

    setBusy(true);
    const result = await postAuthRequest(
      "change-password",
      passwordChangePayload(current, password, confirmation),
    );
    setBusy(false);
    if (!result.ok) {
      setFormError(result.error);
      return;
    }
    setCurrent("");
    setPassword("");
    setConfirmation("");
    setSaved(true);
  }

  const feedback = passwordChangeFeedback(fieldErrors, formError);

  return (
    <Panel
      title="Change Password"
      description={
        apiConfigured
          ? "Change the password for your authenticated account."
          : "Preview the password-change form with sample inputs."
      }
    >
      <form onSubmit={submit} className="max-w-xl space-y-5 p-5" noValidate>
        <p className="text-xs leading-5 text-muted-foreground">
          {apiConfigured
            ? "Your current and new passwords are sent to the authentication service for verification."
            : "No current password is verified; preview changes remain local and nothing is stored."}
        </p>
        {apiConfigured && (
          <PasswordField
            label="Current password"
            value={current}
            onChange={setCurrent}
            autoComplete="current-password"
            disabled={busy}
            error={feedback.currentPasswordError}
          />
        )}
        <PasswordField
          label="New password"
          value={password}
          onChange={setPassword}
          disabled={busy}
          error={feedback.passwordError}
        />
        <p className="text-xs text-muted-foreground">
          {passwordChangePolicyHint(apiConfigured)}
        </p>
        <PasswordField
          label="Confirm new password"
          value={confirmation}
          onChange={setConfirmation}
          disabled={busy}
          error={feedback.confirmationError}
        />
        {feedback.formError && (
          <p role="alert" className="text-sm text-destructive">
            {feedback.formError}
          </p>
        )}
        {saved && (apiConfigured ? (
          <p role="status" className="text-sm text-success">
            Password changed.
          </p>
        ) : (
          <PreviewNotice>
            Password entry and confirmation validated. No password was changed or saved.
          </PreviewNotice>
        ))}
        <Button disabled={busy}>
          {busy
            ? "Submitting…"
            : apiConfigured
              ? "Change password"
              : "Preview password change"}
        </Button>
      </form>
    </Panel>
  );
}
