import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import {
  DEFAULT_EMBED_OPTIONS,
  EmbedOptions,
  encodeEmbedOptions,
} from '@/lib/embed-options';
import { TMarket } from '@/types/market.types';
import { CodeIcon } from '@phosphor-icons/react';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

const TOGGLES: { key: keyof EmbedOptions; label: string }[] = [
  { key: 'chart', label: 'Chart' },
  { key: 'buttons', label: 'Buy buttons' },
  { key: 'volume', label: 'Volume' },
  { key: 'activity', label: 'Live activity' },
  { key: 'yaxis', label: 'Y Axis' },
  { key: 'grid', label: 'Grid rows' },
  { key: 'border', label: 'Border' },
  { key: 'dark', label: 'Dark mode' },
];

export default function EmbedDialog({ market }: { market: TMarket }) {
  const { t } = useTranslation();

  const defaultOutcome =
    [...market.outcomes].sort(
      (a, b) => (b.probability ?? 0) - (a.probability ?? 0),
    )[0] ?? market.outcomes[0];

  const [options, setOptions] = useState<EmbedOptions>({
    ...DEFAULT_EMBED_OPTIONS,
    outcome: defaultOutcome?.id,
  });
  const [width, setWidth] = useState('400');
  const [height, setHeight] = useState('300');
  const [showCode, setShowCode] = useState(false);

  const embedUrl = useMemo(
    () =>
      `${window.location.origin}/embed/markets/${market.slug}?${encodeEmbedOptions(options)}`,
    [market.slug, options],
  );

  const iframeCode = `<iframe src="${embedUrl}" width="${width}" height="${height}" frameborder="0" style="border:none;" title="${market.title}"></iframe>`;

  const set = <K extends keyof EmbedOptions>(key: K, value: EmbedOptions[K]) =>
    setOptions((o) => ({ ...o, [key]: value }));

  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(iframeCode);
      toast.success(t('Embed code copied!'));
    } catch {
      toast.error(t('Failed to copy.'));
    }
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="icon" size="icon" title={t('Embed')}>
          <CodeIcon className="size-5" />
        </Button>
      </DialogTrigger>

      <DialogContent className="sm:max-w-3xl">
        <DialogTitle className="flex items-center gap-2">
          <CodeIcon className="size-5" /> {t('Embed')}
        </DialogTitle>

        <div className="grid gap-6 md:grid-cols-2">
          {/* Controls */}
          <div className="space-y-4">
            <div className="flex items-center justify-between gap-4">
              <Label className="text-sm">{t('Market')}</Label>
              <Select
                value={String(options.outcome ?? '')}
                onValueChange={(v) => set('outcome', Number(v))}
              >
                <SelectTrigger className="h-9 w-44">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {market.outcomes.map((o) => (
                    <SelectItem key={o.id} value={String(o.id)}>
                      {o.title}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-3 border-t border-black/8 pt-3 dark:border-white/8">
              {TOGGLES.map(({ key, label }) => (
                <div
                  key={key}
                  className="flex items-center justify-between gap-4"
                >
                  <span className="text-sm">{t(label)}</span>
                  <Switch
                    checked={Boolean(options[key])}
                    onCheckedChange={(v) => set(key, v as never)}
                  />
                </div>
              ))}
            </div>

            <Button className="w-full" onClick={() => setShowCode((s) => !s)}>
              <CodeIcon className="size-4" />
              {showCode ? t('Hide Code') : t('View Code')}
            </Button>
          </div>

          {/* Preview + sizing */}
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-1.5">
                <Label className="text-xs text-black/50">{t('W')}</Label>
                <Input
                  value={width}
                  onChange={(e) =>
                    setWidth(e.target.value.replace(/[^\d]/g, ''))
                  }
                  className="h-8 w-20"
                  inputMode="numeric"
                />
              </div>
              <div className="flex items-center gap-1.5">
                <Label className="text-xs text-black/50">{t('H')}</Label>
                <Input
                  value={height}
                  onChange={(e) =>
                    setHeight(e.target.value.replace(/[^\d]/g, ''))
                  }
                  className="h-8 w-20"
                  inputMode="numeric"
                />
              </div>
            </div>

            <div className="max-h-[360px] overflow-auto rounded-lg border border-black/10 dark:border-white/10">
              <iframe
                src={embedUrl}
                title={market.title}
                style={{
                  width: `${width || 400}px`,
                  height: `${height || 300}px`,
                  border: 'none',
                }}
              />
            </div>

            {showCode && (
              <div className="space-y-2">
                <textarea
                  readOnly
                  value={iframeCode}
                  onFocus={(e) => e.currentTarget.select()}
                  className="h-24 w-full resize-none rounded-lg border border-black/10 bg-black/5 p-2 font-mono text-xs dark:border-white/10 dark:bg-white/5"
                />
                <Button
                  variant="secondary"
                  className="w-full"
                  onClick={copyCode}
                >
                  {t('Copy Code')}
                </Button>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
