'use client';

import { useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Check, Copy, Link2, Share2, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
  SHARE_PLATFORMS,
  buildPlatformShareUrl,
  canUseNativeShare,
  copyShareLink,
  nativeShare,
  type SharePayload,
} from '@/lib/share';

function ShareBrandIcon({ icon, className }: { icon: string; className?: string }) {
  const props = {
    className,
    viewBox: '0 0 24 24',
    fill: 'currentColor',
    'aria-hidden': true as const,
  };

  switch (icon) {
    case 'facebook':
      return (
        <svg {...props}>
          <path d="M24 12.073C24 5.405 18.627 0 12 0S0 5.405 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073z" />
        </svg>
      );
    case 'whatsapp':
      return (
        <svg {...props}>
          <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.435 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
        </svg>
      );
    case 'messenger':
      return (
        <svg {...props}>
          <path d="M12 0C5.373 0 0 4.975 0 11.111c0 3.497 1.745 6.616 4.472 8.652V24l4.086-2.242c1.09.3 2.246.464 3.442.464 6.627 0 12-4.974 12-11.111C24 4.975 18.627 0 12 0zm1.191 14.963l-3.055-3.26-5.963 3.26L10.732 8.1l3.13 3.26L19.752 8.1l-6.561 6.863z" />
        </svg>
      );
    case 'linkedin':
      return (
        <svg {...props}>
          <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 114.126 0 2.063 2.063 0 01-2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
        </svg>
      );
    case 'x':
      return (
        <svg {...props}>
          <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
        </svg>
      );
    default:
      return <Link2 className={className} />;
  }
}

interface ShareButtonProps {
  payload: SharePayload;
  variant?: 'default' | 'heroOutline' | 'outline' | 'ghost';
  size?: 'sm' | 'default' | 'lg';
  label?: string;
  className?: string;
}

export function ShareButton({
  payload,
  variant = 'outline',
  size = 'sm',
  label = 'Share',
  className,
}: ShareButtonProps) {
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [copied, setCopied] = useState(false);
  const panelId = useId();
  const triggerRef = useRef<HTMLButtonElement>(null);
  const showNativeShare = canUseNativeShare();

  useEffect(() => setMounted(true), []);

  useEffect(() => {
    if (!open) return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false);
    };
    document.addEventListener('keydown', onKeyDown);
    document.body.classList.add('modal-open');
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.classList.remove('modal-open');
      document.body.style.overflow = '';
    };
  }, [open]);

  const handleNativeShare = async () => {
    const shared = await nativeShare(payload);
    if (shared) setOpen(false);
  };

  const handleCopy = async () => {
    await copyShareLink(payload.url);
    setCopied(true);
    window.setTimeout(() => setCopied(false), 2000);
  };

  const openPlatform = (platformId: string) => {
    const href = buildPlatformShareUrl(platformId, payload);
    window.open(href, '_blank', 'noopener,noreferrer,width=600,height=520');
    setOpen(false);
  };

  return (
    <>
      <Button
        ref={triggerRef}
        type="button"
        variant={variant}
        size={size}
        className={cn('gap-1.5', className)}
        aria-expanded={open}
        aria-controls={open ? panelId : undefined}
        onClick={() => setOpen(true)}
      >
        <Share2 className="h-4 w-4" />
        {label}
      </Button>

      {mounted && open
        ? createPortal(
            <div className="fixed inset-0 z-[9999] flex items-end justify-center sm:items-center sm:p-4">
              <button
                type="button"
                className="absolute inset-0 bg-slate-900/50 backdrop-blur-[1px]"
                aria-label="Close share dialog"
                onClick={() => setOpen(false)}
              />

              <div
                id={panelId}
                role="dialog"
                aria-modal="true"
                aria-labelledby={`${panelId}-title`}
                className={cn(
                  'relative z-[10000] flex w-full max-h-[min(92dvh,100dvh)] flex-col',
                  'rounded-t-2xl border border-border bg-surface shadow-2xl',
                  'pb-[env(safe-area-inset-bottom,0px)]',
                  'sm:max-h-[min(85dvh,640px)] sm:max-w-md sm:rounded-2xl sm:pb-0'
                )}
              >
                <div className="flex shrink-0 justify-center pt-2 sm:hidden" aria-hidden>
                  <span className="h-1 w-10 rounded-full bg-slate-200" />
                </div>

                <div className="flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3 sm:px-5 sm:py-4">
                  <div className="min-w-0">
                    <h2 id={`${panelId}-title`} className="text-base font-bold text-slate-900 sm:text-lg">
                      Share
                    </h2>
                    <p className="mt-0.5 text-xs text-muted sm:text-sm">
                      {payload.type === 'job'
                        ? 'Spread the word about this job'
                        : 'Share this worker profile'}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setOpen(false)}
                    className="-mr-1 rounded-lg p-2.5 text-slate-500 hover:bg-slate-100 hover:text-slate-700 sm:mr-0 sm:p-2"
                    aria-label="Close"
                  >
                    <X className="h-5 w-5" />
                  </button>
                </div>

                <div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4 sm:px-5">
                  <div className="rounded-xl border border-border bg-slate-50 p-3.5 sm:p-4">
                    <p className="text-[11px] font-semibold uppercase tracking-wide text-primary">
                      {payload.type === 'job' ? 'Job on eHandyHire' : 'Worker on eHandyHire'}
                    </p>
                    <p className="mt-1 line-clamp-2 font-bold text-slate-900">{payload.title}</p>
                    <p className="mt-1 line-clamp-2 text-sm text-slate-600 sm:line-clamp-3">
                      {payload.description}
                    </p>
                    <p className="mt-3 break-all rounded-lg border border-border bg-white px-3 py-2 text-xs text-slate-500">
                      {payload.url}
                    </p>
                  </div>

                  <p className="mb-2 mt-4 px-0.5 text-[11px] font-semibold uppercase tracking-wide text-muted">
                    Share to
                  </p>

                  <div className="-mx-1 flex gap-3 overflow-x-auto px-1 pb-1 [scrollbar-width:none] sm:hidden [&::-webkit-scrollbar]:hidden">
                    {SHARE_PLATFORMS.map((platform) => (
                      <button
                        key={platform.id}
                        type="button"
                        onClick={() => openPlatform(platform.id)}
                        className="flex w-[4.5rem] shrink-0 flex-col items-center gap-2"
                      >
                        <span
                          className="flex h-12 w-12 items-center justify-center rounded-full text-white shadow-sm"
                          style={{ backgroundColor: platform.color }}
                        >
                          <ShareBrandIcon icon={platform.icon} className="h-5 w-5" />
                        </span>
                        <span className="w-full truncate text-center text-[11px] font-semibold text-slate-700">
                          {platform.label}
                        </span>
                      </button>
                    ))}
                  </div>

                  <div className="hidden gap-2 sm:grid sm:grid-cols-2">
                    {SHARE_PLATFORMS.map((platform) => (
                      <button
                        key={platform.id}
                        type="button"
                        onClick={() => openPlatform(platform.id)}
                        className="flex min-h-11 items-center gap-2.5 rounded-xl border border-border px-3 py-2.5 text-left text-sm font-semibold text-slate-800 transition-colors hover:bg-slate-50 active:bg-slate-100"
                      >
                        <span
                          className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-white"
                          style={{ backgroundColor: platform.color }}
                        >
                          <ShareBrandIcon icon={platform.icon} className="h-4 w-4" />
                        </span>
                        {platform.label}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="shrink-0 border-t border-border bg-surface px-4 py-3 sm:px-5 sm:py-4">
                  <div className="flex flex-col gap-2 sm:flex-row">
                    {showNativeShare ? (
                      <Button
                        type="button"
                        className="h-11 w-full gap-2 sm:flex-1"
                        onClick={handleNativeShare}
                      >
                        <Share2 className="h-4 w-4" />
                        Share via apps
                      </Button>
                    ) : null}
                    <Button
                      type="button"
                      variant={showNativeShare ? 'outline' : 'default'}
                      className="h-11 w-full gap-2 sm:flex-1"
                      onClick={handleCopy}
                    >
                      {copied ? (
                        <Check className="h-4 w-4 text-accent" />
                      ) : (
                        <Copy className="h-4 w-4" />
                      )}
                      {copied ? 'Copied!' : 'Copy link'}
                    </Button>
                  </div>
                </div>
              </div>
            </div>,
            document.body
          )
        : null}
    </>
  );
}
