import type { ReactNode } from "react";
import "./slideout.css";

export type SlideoutSize = "small" | "medium" | "large";
export type SlideoutBreakpoint = "desktop" | "mobile";

export type SlideoutProps = {
  actionLabel?: string;
  breakpoint?: SlideoutBreakpoint;
  children?: ReactNode;
  className?: string;
  closeLabel?: string;
  dir?: "ltr" | "rtl";
  footer?: boolean;
  headerAction?: boolean;
  primaryActionLabel?: string;
  secondaryAction?: boolean;
  secondaryActionLabel?: string;
  size?: SlideoutSize;
  title?: string;
};

type SlideoutSlotExampleProps = {
  dir?: "ltr" | "rtl";
};

function cx(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

export function Slideout({
  actionLabel,
  breakpoint = "desktop",
  children,
  className = "",
  closeLabel,
  dir = "ltr",
  footer = true,
  headerAction = true,
  primaryActionLabel,
  secondaryAction = true,
  secondaryActionLabel,
  size = "small",
  title,
}: SlideoutProps) {
  const rtl = dir === "rtl";
  const hasFooterActions = Boolean(primaryActionLabel || (secondaryAction && secondaryActionLabel));

  return (
    <aside
      className={cx(
        "ds-slideout",
        `ds-slideout--${size}`,
        `ds-slideout--${breakpoint}`,
        rtl && "ds-slideout--rtl",
        className,
      )}
      data-node-id="256:19065"
      dir={dir}
    >
      <section aria-label={title} className="ds-slideout__panel" role="dialog">
        <header className="ds-slideout__header">
          <div className="ds-slideout__heading-wrap">
            <h2 className="ds-slideout__title">{title}</h2>
            {headerAction && actionLabel && (
              <button className="ds-slideout__text-button" type="button">
                {actionLabel}
              </button>
            )}
          </div>
          {closeLabel && (
            <button aria-label={closeLabel} className="ds-slideout__close" type="button">
              <CloseIcon />
            </button>
          )}
        </header>
        <div className="ds-slideout__body">{children}</div>
        {footer && hasFooterActions && (
          <footer className="ds-slideout__footer">
            {primaryActionLabel && (
              <button className="ds-slideout__button ds-slideout__button--primary" type="button">
                {primaryActionLabel}
              </button>
            )}
            {secondaryAction && secondaryActionLabel && (
              <button className="ds-slideout__button ds-slideout__button--secondary" type="button">
                {secondaryActionLabel}
              </button>
            )}
          </footer>
        )}
      </section>
    </aside>
  );
}

export function SlideoutFiltersExample({ dir = "ltr" }: SlideoutSlotExampleProps) {
  const rtl = dir === "rtl";
  const text = rtl
    ? {
        assigned: "مخصصة لـ",
        date: "التاريخ",
        label: "التسمية",
        names: ["أحمد جلال", "عمر مهدي", "هاني هشام", "عمر ماهر"],
        priority: "الأولوية",
        status: "الحالة",
      }
    : {
        assigned: "Assigned to",
        date: "Date",
        label: "Label",
        names: ["Ahmed Galal", "Amr Mahdy", "Hany Hisham", "Omar Maher"],
        priority: "Priority",
        status: "Status",
      };

  return (
    <div className="ds-slideout-slot ds-slideout-filters" data-node-id="256:18779">
      <FilterSection title={text.status}>
        <ChoiceRow kind="checkbox" label={text.label} />
        <ChoiceRow checked kind="checkbox" label={text.label} />
        <ChoiceRow kind="checkbox" label={text.label} />
      </FilterSection>
      <Divider />
      <FilterSection title={text.date}>
        <ChoiceRow kind="radio" label={text.label} />
        <ChoiceRow kind="radio" label={text.label} />
        <ChoiceRow checked kind="radio" label={text.label} />
        <ChoiceRow kind="radio" label={text.label} />
      </FilterSection>
      <Divider />
      <FilterSection title={text.priority}>
        <ChoiceRow kind="checkbox" label={text.label} />
        <ChoiceRow checked kind="checkbox" label={text.label} />
        <ChoiceRow kind="checkbox" label={text.label} />
      </FilterSection>
      <Divider />
      <FilterSection title={text.assigned}>
        {text.names.map((name, index) => (
          <UserChoice key={name} name={name} selected={index === 0 || index === 2} muted={index === 1 || index === 3} />
        ))}
      </FilterSection>
    </div>
  );
}

export function SlideoutUserProfileExample({ dir = "ltr" }: SlideoutSlotExampleProps) {
  const rtl = dir === "rtl";
  const text = rtl
    ? {
        badgeTabs: ["عنصر القائمة", "عنصر القائمة", "عنصر القائمة", "عنصر القائمة"],
        comments: [
          "Lorem ipsum dolor sit amet consectetur @username. Cras in morbi volutpat porttitor se...",
          "",
          "Lorem ipsum dolor sit amet consectetur. Cras in morbi volutpat porttitor semper. Mattis bibendum...",
          "اسم الملف.pdf",
        ],
        name: "أحمد جلال",
        role: "مصمم المنتجات",
        time: "اليوم الساعة 5:20 مساءً",
        titleParts: ["أحمد", "تمت إضافة تعليق جديد في", "#اسم المشروع"],
      }
    : {
        badgeTabs: ["Activity", "Calendar", "My Work", "Asigned"],
        comments: [
          "Lorem ipsum dolor sit amet consectetur @username. Cras in morbi volutpat porttitor se...",
          "",
          "Lorem ipsum dolor sit amet consectetur. Cras in morbi volutpat porttitor semper. Mattis bibendum...",
          "file-name.pdf",
        ],
        name: "Ahmed Galal",
        role: "Product designer",
        time: "Today, 5:20 pm",
        titleParts: ["Ahmed", "added a new comment in", "#project name"],
      };

  return (
    <div className="ds-slideout-slot ds-slideout-profile" data-node-id="256:18872">
      <div className="ds-slideout-profile__header">
        <Avatar name={text.name} online size="large" />
        <div className="ds-slideout-profile__identity">
          <p className="ds-slideout-profile__name">{text.name}</p>
          <p className="ds-slideout-profile__role">{text.role}</p>
        </div>
      </div>
      <div aria-label={rtl ? "علامات تبويب الملف الشخصي" : "Profile tabs"} className="ds-slideout-profile__tabs" role="tablist">
        {text.badgeTabs.map((tab, index) => (
          <button aria-selected={index === 0 || (rtl && index === 3)} className="ds-slideout-profile__tab" key={`${tab}-${index}`} role="tab" type="button">
            <span>{tab}</span>
            {(index === 2 || index === 3) && !rtl && <span className="ds-slideout-profile__badge">{index === 2 ? "2" : "4"}</span>}
          </button>
        ))}
      </div>
      <div className="ds-slideout-feed">
        {text.comments.map((comment, index) => (
          <FeedItem comment={comment} index={index} key={`${comment}-${index}`} rtl={rtl} time={text.time} titleParts={text.titleParts} />
        ))}
      </div>
    </div>
  );
}

export function SlideoutPaymentDetailExample({ dir = "ltr" }: SlideoutSlotExampleProps) {
  const rtl = dir === "rtl";
  const text = rtl
    ? {
        amount: "9,453,50 دولار",
        copy: "نسخة",
        date: "24 مايو، 2050، 10:23 صباحًا",
        details: "التفاصيل",
        id: "معرف المعاملة",
        name: "جاكوب جونز",
        rows: [
          ["المبلغ", "9,553,50 دولار"],
          ["الرسوم", "$100 دولار"],
          ["الإجمالي", "9,453,50 دولار"],
        ],
        showStory: "عرض القصة",
      }
    : {
        amount: "$9,453,50",
        copy: "Copy",
        date: "24 May, 2050, 10:23 AM",
        details: "Details",
        id: "Transaction ID",
        name: "Jacob Jones",
        rows: [
          ["Amount", "$9,553,50"],
          ["Fee", "$100"],
          ["Total", "$9,453,50"],
        ],
        showStory: "Show story",
      };

  return (
    <div className="ds-slideout-slot ds-payment-detail" data-node-id="256:18901">
      <section className="ds-payment-detail__hero">
        <div className="ds-payment-detail__user">
          <Avatar name={text.name} size="medium" />
          <div>
            <p className="ds-payment-detail__name">{text.name}</p>
            <p className="ds-payment-detail__muted">useraccount@gmail.com</p>
          </div>
        </div>
        <div>
          <p className="ds-payment-detail__amount">{text.amount}</p>
          <p className="ds-payment-detail__date">{text.date}</p>
        </div>
      </section>
      <section className="ds-payment-card">
        <h3>{text.details}</h3>
        <div className="ds-payment-detail__rows">
          {text.rows.map(([label, value]) => (
            <div className="ds-payment-detail__row" key={label}>
              <span>{label}</span>
              <strong>{value}</strong>
            </div>
          ))}
        </div>
      </section>
      <section className="ds-payment-card">
        <h3>{text.id}</h3>
        <div className="ds-payment-detail__transaction">
          <span>45FWGERT54GSGY54WRE</span>
          <button className="ds-slideout__button ds-slideout__button--secondary ds-payment-detail__copy" type="button">
            {text.copy}
          </button>
        </div>
      </section>
      <button className="ds-payment-detail__story" type="button">
        {text.showStory}
      </button>
    </div>
  );
}

export function SlideoutPaymentFormExample({ dir = "ltr" }: SlideoutSlotExampleProps) {
  const rtl = dir === "rtl";
  const text = rtl
    ? {
        amount: "8,425.32 دولار",
        category: "الفئة",
        date: "31 مايو 2023 الساعة 09:42 صباحًا",
        export: "تصدير",
        fields: [
          ["BIC", "سيتيكسكس2X"],
          ["رقم الحساب المصرفي الدولي", "**** **** 4356 29"],
          ["باعث", "الشريط"],
          ["المرجع", "الشريط"],
          ["التاريخ", "31/05/2050"],
          ["العلامة", "الشريط"],
          ["التاريخ", "8,425.32 دولار"],
          ["الحالة", "البدء"],
        ],
        receipts: "الإيصالات",
        select: "السحب الآلي",
        uploadHelp: "نقبل ملفات PDF وJPG وPNG بحجم يصل إلى 10 ميجابايت",
        uploadTitle: "انقر لتحديد الملفات أو إسقاطها",
      }
    : {
        amount: "$8,425.32",
        category: "Category",
        date: "31 May, 2023, 09:42 AM",
        export: "Export",
        fields: [
          ["IBAN", "**** **** 4356 29"],
          ["BIC", "CITIXX2X"],
          ["Reference", "STRIPE"],
          ["Emitter", "Stripe"],
          ["Tag", "Stripe"],
          ["Date", "05/31/2050"],
          ["Status", "Initiated"],
          ["Date", "$8,425.32"],
        ],
        receipts: "Receipts",
        select: "Automated Cashout",
        uploadHelp: "We accept PDF, JPG and PNG files up to 10MB",
        uploadTitle: "Click to select or drop files",
      };

  return (
    <div className="ds-slideout-slot ds-payment-form" data-node-id="256:18964">
      <section className="ds-payment-form__amount">
        <CompanyIcon />
        <div className="ds-payment-form__amount-copy">
          <p className="ds-payment-form__value">{text.amount}</p>
          <p className="ds-payment-form__date">{text.date}</p>
        </div>
        <button className="ds-slideout__button ds-slideout__button--secondary ds-payment-form__export" type="button">
          {text.export}
        </button>
      </section>
      <section className="ds-payment-card ds-payment-form__grid">
        {text.fields.map(([label, value], index) => (
          <div className="ds-payment-form__field" key={`${label}-${index}`}>
            <span>{label}</span>
            <strong>{value}</strong>
          </div>
        ))}
      </section>
      <section className="ds-payment-card ds-payment-form__section">
        <h3>{text.category}</h3>
        <button className="ds-payment-form__select" type="button">
          <span>{text.select}</span>
          <ChevronDownIcon />
        </button>
      </section>
      <section className="ds-payment-card ds-payment-form__section">
        <h3>{text.receipts}</h3>
        <div className="ds-payment-form__upload">
          <span className="ds-payment-form__upload-icon">
            <UploadCloudIcon />
          </span>
          <span className="ds-payment-form__upload-copy">
            <strong>{text.uploadTitle}</strong>
            <span>{text.uploadHelp}</span>
          </span>
        </div>
      </section>
    </div>
  );
}

function FilterSection({ children, title }: { children: ReactNode; title: string }) {
  return (
    <section className="ds-filter-section">
      <h3>{title}</h3>
      <div className="ds-filter-section__content">{children}</div>
    </section>
  );
}

function ChoiceRow({ checked = false, kind, label }: { checked?: boolean; kind: "checkbox" | "radio"; label: string }) {
  return (
    <div className="ds-choice-row">
      <span aria-hidden="true" className={cx("ds-choice-row__control", `ds-choice-row__control--${kind}`, checked && "is-checked")}>
        {checked && kind === "checkbox" && <CheckIcon />}
        {checked && kind === "radio" && <span className="ds-choice-row__dot" />}
      </span>
      <span className="ds-choice-row__label">{label}</span>
    </div>
  );
}

function UserChoice({ muted = false, name, selected = false }: { muted?: boolean; name: string; selected?: boolean }) {
  return (
    <div className="ds-user-choice">
      <div className="ds-user-choice__person">
        <Avatar name={name} size="small" />
        <span className={cx(muted && "is-muted")}>{name}</span>
      </div>
      {selected && <CheckIcon className="ds-user-choice__check" />}
    </div>
  );
}

function FeedItem({
  comment,
  index,
  rtl,
  time,
  titleParts,
}: {
  comment: string;
  index: number;
  rtl: boolean;
  time: string;
  titleParts: string[];
}) {
  return (
    <article className="ds-feed-item">
      <div className="ds-feed-item__heading">
        <div className="ds-feed-item__copy">
          <p>
            <strong>{titleParts[0]}</strong> <span>{titleParts[1]}</span> <a href="#top">{titleParts[2]}</a>
          </p>
          <time>{time}</time>
        </div>
        <span aria-hidden="true" className="ds-feed-item__indicator" />
      </div>
      {index === 1 ? (
        <div className="ds-feed-item__images">
          <span className="ds-feed-item__image ds-feed-item__image--one" />
          <span className="ds-feed-item__image ds-feed-item__image--two" />
        </div>
      ) : index === 3 ? (
        <div className="ds-feed-item__files">
          <FileRow label={comment} rtl={rtl} />
          <FileRow label={rtl ? "اسم الملف الثاني.pdf" : "Second file-name.pdf"} rtl={rtl} />
        </div>
      ) : (
        <p className="ds-feed-item__comment">{comment}</p>
      )}
    </article>
  );
}

function FileRow({ label, rtl }: { label: string; rtl: boolean }) {
  return (
    <div className="ds-file-row">
      <PaperclipIcon />
      <span>{label}</span>
      <button type="button">{rtl ? "تنزيل" : "Download"}</button>
    </div>
  );
}

function Avatar({ name, online = false, size = "small" }: { name: string; online?: boolean; size?: "small" | "medium" | "large" }) {
  const initials = name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0])
    .join("");

  return (
    <span className={cx("ds-avatar", `ds-avatar--${size}`)} aria-label={name} role="img">
      <span>{initials}</span>
      {online && <span aria-hidden="true" className="ds-avatar__status" />}
    </span>
  );
}

function CompanyIcon() {
  return (
    <span aria-hidden="true" className="ds-company-icon">
      <span />
    </span>
  );
}

function Divider() {
  return <span aria-hidden="true" className="ds-slideout-divider" />;
}

function CloseIcon() {
  return (
    <svg aria-hidden="true" fill="none" height="20" viewBox="0 0 20 20" width="20">
      <path d="m5.25 5.25 9.5 9.5m0-9.5-9.5 9.5" stroke="currentColor" strokeLinecap="round" strokeWidth="1.8" />
    </svg>
  );
}

function CheckIcon({ className = "" }: { className?: string }) {
  return (
    <svg aria-hidden="true" className={className} fill="none" height="14" viewBox="0 0 14 14" width="14">
      <path d="m3 7.1 2.4 2.4L10.6 4.5" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" />
    </svg>
  );
}

function ChevronDownIcon() {
  return (
    <svg aria-hidden="true" fill="none" height="20" viewBox="0 0 20 20" width="20">
      <path d="m5.5 7.5 4.5 4.5 4.5-4.5" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.7" />
    </svg>
  );
}

function PaperclipIcon() {
  return (
    <svg aria-hidden="true" fill="none" height="20" viewBox="0 0 20 20" width="20">
      <path d="m7.4 10.9 4.5-4.5a2.6 2.6 0 1 1 3.7 3.7l-6.2 6.2a4 4 0 0 1-5.7-5.7l6.3-6.3" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.6" />
    </svg>
  );
}

function UploadCloudIcon() {
  return (
    <svg aria-hidden="true" fill="none" height="20" viewBox="0 0 20 20" width="20">
      <path d="M7 13.5H5.8a3.3 3.3 0 0 1-.6-6.5 4.6 4.6 0 0 1 8.6-1.8 3.7 3.7 0 0 1 .6 7.3H13M10 8v7m0-7-2.4 2.4M10 8l2.4 2.4" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" />
    </svg>
  );
}
