import { zodResolver } from '@hookform/resolvers/zod';
import { SkillsSchema, type Skills } from '../../../content/schemas/skills';
import { FormShell } from '../FormShell';
import { Section } from '../Section';
import { TextField } from '../fields/TextField';
import { SelectField } from '../fields/SelectField';
import { EmojiField } from '../fields/EmojiField';
import { ArrayEditor } from '../fields/ArrayEditor';

type Props = { defaultValues: Skills };

const LEVEL_OPTIONS = [
  { value: 'primary', label: 'Primary' },
  { value: 'secondary', label: 'Secondary' },
];

function CategoryArray({ root, label, subtitle }: { root: 'primary' | 'secondary'; label: string; subtitle?: string }) {
  return (
    <Section title={label} subtitle={subtitle}>
      <ArrayEditor
        name={root}
        label="Catégories"
        newItem={() => ({ id: '', label: '', items: [] as { name: string; icon: string; level: 'primary' | 'secondary' }[] })}
        itemLabel={(i) => `catégorie #${String(i + 1).padStart(2, '0')}`}
      >
        {({ namePrefix }) => (
          <>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <TextField name={`${namePrefix}.id`} label="ID" hint="Slug interne, ex : front, devops" />
              <TextField name={`${namePrefix}.label`} label="Label affiché" />
            </div>
            <ArrayEditor
              name={`${namePrefix}.items`}
              label="Skills"
              newItem={() => ({ name: '', icon: '⚡', level: 'primary' as const })}
              itemLabel={(i) => `skill #${String(i + 1).padStart(2, '0')}`}
            >
              {({ namePrefix: skillName }) => (
                <>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <TextField name={`${skillName}.name`} label="Nom" />
                    <SelectField
                      name={`${skillName}.level`}
                      label="Niveau"
                      options={LEVEL_OPTIONS}
                    />
                  </div>
                  <EmojiField
                    name={`${skillName}.icon`}
                    label="Icône"
                    hint="Emoji ou caractère court (slug iconify supporté)"
                  />
                </>
              )}
            </ArrayEditor>
          </>
        )}
      </ArrayEditor>
    </Section>
  );
}

export function SkillsForm({ defaultValues }: Props) {
  return (
    <FormShell<Skills>
      section="skills"
      defaultValues={defaultValues as never}
      resolver={zodResolver(SkillsSchema) as never}
    >
      <CategoryArray root="primary" label="Stack primaire" subtitle="// rack 1" />
      <CategoryArray root="secondary" label="Stack secondaire" subtitle="// rack 2" />
    </FormShell>
  );
}
