
import { useMemo, useState } from 'preact/hooks';
import { registerModule, type AsukaModuleComponent } from '../../core/modules';
import { getI18n } from '../../core/i18n';
import { useT } from '../../hooks/useT';
import { useAsukaStore } from '../../store/asukaStore';
import { normalizePriceInput, type AsukaPriceInput } from '../../core/pricingValue';

import { Card, CardHeader, CardTitle, CardContent } from '../core/Card';
import { Field } from '../core/Field';
import { Input } from '../core/Input';
import { Button } from '../core/Button';
import { List } from '../core/List';

export type DesignItem = {
  url: string;
  name: string;
  price?: AsukaPriceInput;
  category?: string;
};

export const DesignsPanel: AsukaModuleComponent = ({ context }) => {
  const engine = context.getEngine?.() ?? null;
  const t = useT();

  const rawDesigns = useAsukaStore((s: any) => (s.moduleConfig?.designs?.items ?? [])) as DesignItem[];
  const designs = useMemo(() => (rawDesigns ?? []).map((item) => {
    const price = normalizePriceInput((item as any)?.price);
    return { ...(item ?? {}), price } as DesignItem;
  }), [rawDesigns]);

  const [query, setQuery] = useState('');
  const [category, setCategory] = useState<string>('');

  const categories = useMemo(() => {
    const set = new Set<string>();
    for (const d of designs) {
      const c = (d?.category ?? '').trim();
      if (c) set.add(c);
    }
    return Array.from(set).sort((a, b) => a.localeCompare(b));
  }, [designs]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    const cat = category.trim();
    return (designs ?? []).filter((d) => {
      if (!d?.url) return false;
      if (cat && (d.category ?? '') !== cat) return false;
      if (!q) return true;
      const hay = `${d.name ?? ''} ${d.category ?? ''}`.toLowerCase();
      return hay.includes(q);
    });
  }, [designs, query, category]);

  const addToCanvas = async (item: DesignItem) => {
    if (!item?.url) return;
    const price = normalizePriceInput(item.price);
    await engine?.objects.addDesign({
      url: item.url,
      name: item.name,
      price,
      metadata: { category: item.category, sourceModule: 'designs', itemGroup: 'Designs', center: true },
    });
  };

  return (
    <Card>
      <CardHeader className="ask-flex ask-items-center ask-justify-between ask-gap-2">
        <CardTitle>{t('modules.designs')}</CardTitle>
        <span className="ask-text-[10px] ask-text-textMuted">{filtered.length}/{designs.length}</span>
      </CardHeader>

      <CardContent className="ask-flex ask-flex-col ask-gap-4">
        <Field label={t('common.search')}>
          <Input
            value={query}
            onInput={(e) => setQuery((e.target as HTMLInputElement).value)}
            placeholder={t('ui.search_designs')}
          />
        </Field>

        {categories.length ? (
          <div className="ask-flex ask-flex-wrap ask-gap-2">
            <Button
              size="sm"
              variant={category ? 'ghost' : 'primary'}
              onClick={() => setCategory('')}
            >{t('ui.all','All')}</Button>
            {categories.map((c) => (
              <Button
                key={c}
                size="sm"
                variant={category === c ? 'primary' : 'ghost'}
                onClick={() => setCategory(c)}
              >
                {c}
              </Button>
            ))}
          </div>
        ) : null}

        <List
          items={filtered}
          columns={2}
          getKey={(it) => `${it.url}-${it.name}`}
          empty={
            <div className="ask-text-[10px] ask-text-textMuted">{t('ui.no_designs_provide_them_at_init_via')}<code className="ask-rounded ask-bg-surface ask-px-1">{t('ui.designs_items_path')}</code>.
            </div>
          }
          renderItem={(it) => (
            <div className="ask-overflow-hidden ask-rounded-[14px] ask-border ask-border-borderSubtle ask-bg-surfaceAlt">
              <button
                type="button"
                className="ask-block ask-w-full"
                onClick={() => addToCanvas(it)}
                title={t('ui.add_to_canvas')}
              >
                <img
                  src={it.url}
                  alt={it.name}
                  className="ask-h-24 ask-w-full ask-object-contain ask-bg-surface"
                  loading="lazy"
                  decoding="async"
                  draggable={false}
                />
              </button>

              <div className="ask-flex ask-flex-col ask-gap-1 ask-p-2">
                <div className="ask-flex ask-items-start ask-justify-between ask-gap-2">
                  <div className="ask-text-[11px] ask-font-medium ask-leading-4 ask-line-clamp-2">{it.name}</div>
                  {typeof it.price === 'number' ? (
                    <div className="ask-shrink-0 ask-rounded-full ask-bg-surface ask-px-2 ask-py-0.5 ask-text-[10px] ask-text-textMuted">
                      {it.price.toFixed(2)}€
                    </div>
                  ) : null}
                </div>
                {it.category ? (
                  <div className="ask-text-[10px] ask-text-textMuted">{it.category}</div>
                ) : null}

                <div className="ask-mt-1">
                  <Button size="sm" onClick={() => addToCanvas(it)}>{t('common.add','Add')}</Button>
                </div>
              </div>
            </div>
          )}
        />
      </CardContent>
    </Card>
  );
};

registerModule({
  id: 'designs',
  label: getI18n().t('modules.designs'),
  icon: 'brush',
  displayMode: 'floating',
  supportedEngines: ['fabric', '3d'],
  requiredCapabilities: ['addDesign'],
  keepMounted: true,
  render: DesignsPanel,
});

export default DesignsPanel;
