"use client";

import { useState } from "react";
import { KeyRound, Save, User } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Button, Card, CardHeader, Field, Input, KeyValue, PageHeader, useToast } from "@/components/ui";
import { formatDate } from "@/lib/utils";

export default function PortalProfilePage() {
  const toast = useToast();
  const { data, loading } = useApi<{
    customer: {
      customerCode: string;
      name: string;
      mobile: string;
      email: string | null;
      address: string | null;
      status: string;
      internetStatus: string;
      expiryDate: string | null;
      monthlyPrice: string;
      registrationDate: string;
      packageName: string | null;
      speed: string | null;
      pppoeUsername: string | null;
      routerName: string | null;
    };
  }>("/api/portal");

  const [form, setForm] = useState({ email: "", address: "" });
  const [passwords, setPasswords] = useState({ currentPassword: "", newPassword: "", confirmPassword: "" });
  const [busy, setBusy] = useState(false);

  if (loading && !data) return <div className="skeleton h-96 rounded-2xl" />;

  return (
    <>
      <PageHeader title="My profile" subtitle="Account details, package and security" icon={<User className="h-5 w-5" />} />

      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader title="Account information" icon={<User className="h-4 w-4" />} />
          <div className="p-4">
            <KeyValue
              items={[
                { label: "Customer ID", value: data?.customer.customerCode },
                { label: "Name", value: data?.customer.name },
                { label: "Mobile", value: data?.customer.mobile },
                { label: "Email", value: data?.customer.email ?? "—" },
                { label: "Address", value: data?.customer.address ?? "—" },
                { label: "Package", value: `${data?.customer.packageName ?? "—"} (${data?.customer.speed ?? "—"})` },
                { label: "PPPoE username", value: data?.customer.pppoeUsername ?? "—" },
                { label: "Serving router", value: data?.customer.routerName ?? "—" },
                { label: "Customer since", value: formatDate(data?.customer.registrationDate) },
                { label: "Next expiry", value: formatDate(data?.customer.expiryDate) },
              ]}
            />
          </div>
        </Card>

        <div className="space-y-4">
          <Card>
            <CardHeader title="Update contact details" subtitle="Changes are reviewed by support" icon={<Save className="h-4 w-4" />} />
            <div className="grid gap-4 p-4">
              <Field label="Email">
                <Input value={form.email || String(data?.customer.email ?? "")} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </Field>
              <Field label="Address">
                <Input value={form.address || String(data?.customer.address ?? "")} onChange={(e) => setForm({ ...form, address: e.target.value })} />
              </Field>
              <Button
                loading={busy}
                onClick={async () => {
                  setBusy(true);
                  try {
                    await api("/api/portal", { method: "PATCH", json: form });
                    toast.push("Contact details updated", "success");
                  } catch (err) {
                    toast.push(err instanceof Error ? err.message : "Update failed", "error");
                  } finally {
                    setBusy(false);
                  }
                }}
              >
                Save details
              </Button>
            </div>
          </Card>

          <Card>
            <CardHeader title="Change password" subtitle="Used for this portal login" icon={<KeyRound className="h-4 w-4" />} />
            <div className="grid gap-4 p-4">
              <Field label="Current password">
                <Input type="password" value={passwords.currentPassword} onChange={(e) => setPasswords({ ...passwords, currentPassword: e.target.value })} />
              </Field>
              <div className="grid gap-4 sm:grid-cols-2">
                <Field label="New password">
                  <Input type="password" value={passwords.newPassword} onChange={(e) => setPasswords({ ...passwords, newPassword: e.target.value })} />
                </Field>
                <Field label="Confirm password">
                  <Input type="password" value={passwords.confirmPassword} onChange={(e) => setPasswords({ ...passwords, confirmPassword: e.target.value })} />
                </Field>
              </div>
              <Button
                variant="secondary"
                loading={busy}
                onClick={async () => {
                  setBusy(true);
                  try {
                    await api("/api/auth/change-password", { method: "POST", json: passwords });
                    toast.push("Password updated", "success");
                    setPasswords({ currentPassword: "", newPassword: "", confirmPassword: "" });
                  } catch (err) {
                    toast.push(err instanceof Error ? err.message : "Update failed", "error");
                  } finally {
                    setBusy(false);
                  }
                }}
              >
                Update password
              </Button>
              <p className="text-[11px] text-slate-500">To change your PPPoE password, please contact support — it must be pushed to the router.</p>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}
