"use client";

import { useEffect, useState } from "react";
import { Card } from "@/components/ui";
import { KeyRound, ExternalLink, Copy, Eye, EyeOff, Check } from "lucide-react";

type Info = { url: string; username: string; password: string | null };

export function CompanyDashboardCard() {
  const [info, setInfo] = useState<Info | null>(null);
  const [loading, setLoading] = useState(true);
  const [show, setShow] = useState(false);
  const [copied, setCopied] = useState("");

  useEffect(() => {
    fetch("/api/company/dashboard")
      .then((r) => r.json())
      .then((b) => setInfo(b.company))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function copy(label: string, value: string) {
    await navigator.clipboard.writeText(value);
    setCopied(label);
    setTimeout(() => setCopied(""), 1500);
  }

  if (loading || !info) return null;

  return (
    <Card dir="rtl">
      <div className="mb-3 flex items-center gap-2 text-sm font-semibold text-ink">
        <KeyRound size={18} className="text-brand" /> بيانات دخول لوحة موظفيك
      </div>
      <p className="mb-4 text-sm text-slate-500">
        كل موظفيك يتشاركون لوحة واحدة — سجّل الدخول ثم اختر الوكيل من مبدّل الحسابات في الأعلى.
      </p>
      <div className="grid gap-3 sm:grid-cols-3">
        <Field label="الرابط" mono>
          <a href={info.url} target="_blank" className="inline-flex items-center gap-1 text-brand hover:underline">
            {info.url.replace("https://", "")}
            <ExternalLink size={13} />
          </a>
        </Field>

        <Field label="اسم المستخدم" mono onCopy={() => copy("user", info.username)} copied={copied === "user"}>
          {info.username}
        </Field>

        <Field
          label="كلمة المرور"
          mono
          onCopy={info.password ? () => copy("pw", info.password!) : undefined}
          copied={copied === "pw"}
          extra={
            info.password && (
              <button onClick={() => setShow((s) => !s)} className="text-slate-400 hover:text-ink">
                {show ? <EyeOff size={14} /> : <Eye size={14} />}
              </button>
            )
          }
        >
          {info.password ? (show ? info.password : "•".repeat(12)) : "—"}
        </Field>
      </div>
    </Card>
  );
}

function Field({
  label,
  children,
  mono,
  onCopy,
  copied,
  extra,
}: {
  label: string;
  children: React.ReactNode;
  mono?: boolean;
  onCopy?: () => void;
  copied?: boolean;
  extra?: React.ReactNode;
}) {
  return (
    <div className="rounded-lg border border-slate-200 p-3">
      <span className="text-xs font-semibold uppercase tracking-wide text-slate-400">{label}</span>
      <div className="mt-1 flex items-center justify-between gap-2">
        <span className={`min-w-0 truncate text-sm text-ink ${mono ? "font-mono" : ""}`}>{children}</span>
        <span className="flex shrink-0 items-center gap-1.5">
          {extra}
          {onCopy && (
            <button onClick={onCopy} className="text-slate-400 hover:text-brand" title="نسخ">
              {copied ? <Check size={14} className="text-emerald-500" /> : <Copy size={14} />}
            </button>
          )}
        </span>
      </div>
    </div>
  );
}
