'use client';

import { useEffect, useState } from 'react';
import { GraduationCap, Wrench, Loader2 } from 'lucide-react';
import { api } from '@/lib/api';
import { getCategoryTl } from '@/lib/categoryTl';
import { t, type RegisterLang } from '@/lib/registerLang';
import { cn } from '@/lib/utils';

export interface CategoryOption {
  id: string;
  name: string;
  slug: string;
  icon?: string;
}

interface SkillPickerProps {
  value: string[];
  onChange: (categoryIds: string[]) => void;
  otherSkills?: string;
  onOtherSkillsChange?: (value: string) => void;
  isStudent?: boolean;
  onIsStudentChange?: (value: boolean) => void;
  error?: string;
  otherSkillsError?: string;
  lang?: RegisterLang;
}

export function hasWorkerSkillSelection(categoryIds: string[], otherSkills: string): boolean {
  return categoryIds.length > 0 || otherSkills.trim().length >= 2;
}

export function SkillPicker({
  value,
  onChange,
  otherSkills = '',
  onOtherSkillsChange,
  isStudent = false,
  onIsStudentChange,
  error,
  otherSkillsError,
  lang = 'en',
}: SkillPickerProps) {
  const [categories, setCategories] = useState<CategoryOption[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api<{ data: CategoryOption[] }>('/categories?limit=50')
      .then((res) => setCategories(res.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const toggle = (categoryId: string) => {
    if (value.includes(categoryId)) {
      onChange(value.filter((id) => id !== categoryId));
    } else {
      onChange([...value, categoryId]);
    }
  };

  const listedCategories = categories.filter((cat) => cat.slug !== 'other');

  return (
    <div className="space-y-4">
      <div className="space-y-2">
        <label className="text-sm font-medium text-slate-700 flex items-center gap-1.5">
          <Wrench className="h-4 w-4 text-primary" />
          {t(lang, 'Skills & trades', 'Mga kasanayan at trabaho')}
        </label>
        <p className="text-xs text-muted leading-relaxed">
          {t(
            lang,
            'Select all services you offer — customers can find you by any of these skills.',
            'Piliin lahat ng serbisyo na kaya mo — dito ka mahahanap ng mga customer.'
          )}
        </p>
        {loading ? (
          <div className="flex items-center gap-2 py-4 text-sm text-muted">
            <Loader2 className="h-4 w-4 animate-spin" />
            {t(lang, 'Loading trades...', 'Kinukuha ang listahan...')}
          </div>
        ) : (
          <div className="flex flex-wrap gap-2">
            {listedCategories.map((cat) => {
              const selected = value.includes(cat.id);
              const tlName = getCategoryTl(cat.slug)?.nameTl;
              const label = lang === 'tl' && tlName ? tlName : cat.name;
              return (
                <button
                  key={cat.id}
                  type="button"
                  onClick={() => toggle(cat.id)}
                  title={tlName ? `${cat.name} / ${tlName}` : cat.name}
                  className={cn('filter-chip gap-1.5', selected && 'filter-chip-active')}
                >
                  <span aria-hidden>{cat.icon || '🔧'}</span>
                  {label}
                </button>
              );
            })}
          </div>
        )}
        {error && <p className="text-sm text-red-500">{error}</p>}
        {!loading && value.length > 0 && (
          <p className="text-xs text-muted">
            {t(
              lang,
              `${value.length} skill${value.length !== 1 ? 's' : ''} selected`,
              `${value.length} kasanayan ang napili`
            )}
          </p>
        )}
      </div>

      {onOtherSkillsChange && (
        <div className="space-y-1.5 pt-1 border-t border-border">
          <label htmlFor="other-skills" className="text-sm font-medium text-slate-700">
            {t(lang, 'Skill not listed?', 'Walang katulad sa listahan?')}
          </label>
          <p className="text-xs text-muted leading-relaxed">
            {t(
              lang,
              'Describe other services you offer (e.g. embroidery, PC repair, event help).',
              'Ilagay ang iba pang serbisyo mo (hal. embroidery, PC repair, tulong sa event).'
            )}
          </p>
          <textarea
            id="other-skills"
            value={otherSkills}
            onChange={(e) => onOtherSkillsChange(e.target.value)}
            placeholder={t(
              lang,
              'e.g. Laptop repair, henna art, tutoring math...',
              'hal. Laptop repair, henna art, tutoring math...'
            )}
            rows={2}
            maxLength={200}
            className={cn(
              'search-input w-full resize-y min-h-[72px] py-2.5',
              otherSkillsError && 'border-red-500 focus:ring-red-500/20 focus:border-red-500'
            )}
          />
          {otherSkillsError && <p className="text-sm text-red-500">{otherSkillsError}</p>}
        </div>
      )}

      {onIsStudentChange && (
        <label className="flex items-start gap-3 cursor-pointer rounded-xl border border-border bg-white p-4">
          <input
            type="checkbox"
            checked={isStudent}
            onChange={(e) => onIsStudentChange(e.target.checked)}
            className="mt-0.5 h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
          />
          <span className="space-y-0.5">
            <span className="flex items-center gap-1.5 text-sm font-semibold text-slate-900">
              <GraduationCap className="h-4 w-4 text-primary" />
              {t(lang, "I'm a student looking to earn", 'Estudyante ako at naghahanap ng kita')}
            </span>
            <span className="block text-xs text-muted leading-relaxed">
              {t(
                lang,
                "Show customers you're a student available for part-time or flexible work.",
                'Ipakita sa customer na estudyante ka at available sa part-time o flexible work.'
              )}
            </span>
          </span>
        </label>
      )}
    </div>
  );
}
