import { Plus, Save, Trash2, X } from 'lucide-react';

import type {
  SignLanguageDraft,
  SignLanguagePage,
} from '@/business/sign-language/types';
import { ImageUpload } from '@/components/common/ImageUpload';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { NativeSelect } from '@/components/ui/native-select';
import { Textarea } from '@/components/ui/textarea';
import { SIGN_LANGUAGE_CATEGORY_FILTERS } from '@/shared/constants/signLanguage';
import type { SignItem } from '@/shared/types/app';

interface SignLanguageManagementPanelProps {
  readonly page: SignLanguagePage;
}

type DraftField = keyof SignLanguageDraft;

interface SignAssetSectionProps {
  readonly title: string;
  readonly urlLabel: string;
  readonly uploadLabel: string;
  readonly value: string;
  readonly placeholder: string;
  readonly uploadField: string;
  readonly onChange: (value: string) => void;
}

function toSignCategory(value: string): SignItem['category'] {
  switch (value) {
    case 'emotional':
    case 'classroom':
      return value;
    case 'basic-needs':
    default:
      return 'basic-needs';
  }
}

function SignAssetSection({
  title,
  urlLabel,
  uploadLabel,
  value,
  placeholder,
  uploadField,
  onChange,
}: SignAssetSectionProps) {
  return (
    <fieldset className="rounded-xl border border-slate-700/60 bg-slate-900/45 p-4">
      <legend className="px-1 text-sm font-semibold text-slate-100">{title}</legend>
      <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
        <label className="space-y-2 text-sm font-medium text-slate-300">
          {urlLabel}
          <Input
            value={value}
            onChange={(event) => onChange(event.target.value)}
            placeholder={placeholder}
          />
        </label>
        <div className="md:min-w-64">
          <ImageUpload
            value={value || null}
            onChange={(privateUrl) => onChange(privateUrl ?? '')}
            table="sign-language"
            field={uploadField}
            label={uploadLabel}
          />
        </div>
      </div>
    </fieldset>
  );
}

export function SignLanguageManagementPanel({ page }: SignLanguageManagementPanelProps) {
  if (!page.canManageSigns) {
    return null;
  }

  const draft = page.signDraft;

  function updateTextField(field: DraftField, value: string) {
    page.updateSignDraft({ [field]: value });
  }

  return (
    <section className="rounded-2xl border border-slate-700/50 bg-slate-900/45 overflow-hidden">
      <div className="flex flex-col gap-3 border-b border-slate-700/50 px-5 py-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <h3 className="text-lg font-semibold text-white">Manage Sign Cards</h3>
          <p className="text-sm text-slate-400">Organization-level sign library and weekly focus</p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
          <label className="flex w-full flex-col gap-1.5 text-xs font-medium text-slate-300 sm:w-64 lg:w-72">
            <span>Sign of the Week</span>
            <NativeSelect
              value={page.signOfWeekId ?? ''}
              onChange={(event) => page.selectSignOfWeek(event.target.value)}
              disabled={page.isSavingSigns || page.signs.length === 0}
              className="h-10 rounded-lg border-slate-700 bg-slate-950/70 text-sm"
            >
              <option value="" disabled>Select a sign</option>
              {page.signs.map((sign) => (
                <option key={sign.id} value={sign.id}>
                  {sign.word}
                </option>
              ))}
            </NativeSelect>
          </label>
          <Button
            type="button"
            onClick={page.startCreateSign}
            disabled={page.isSavingSigns}
            leadingIcon={<Plus size={16} />}
            className="h-10 shrink-0 rounded-lg bg-emerald-600 px-4 text-sm text-white hover:bg-emerald-500"
          >
            Add Sign
          </Button>
        </div>
      </div>

      <div className="space-y-5 p-5">
        {draft && (
          <div className="rounded-xl border border-slate-700/60 bg-slate-950/35 p-4">
            <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <h4 className="text-base font-semibold text-white">
                {page.signDraftMode === 'create' ? 'New Sign' : 'Edit Sign'}
              </h4>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={page.cancelSignDraft}
                leadingIcon={<X size={16} />}
              >
                Cancel
              </Button>
            </div>

            <div className="grid gap-4 lg:grid-cols-2">
              <label className="space-y-2 text-sm font-medium text-slate-300">
                Title
                <Input
                  value={draft.word}
                  onChange={(event) => updateTextField('word', event.target.value)}
                  placeholder="Help"
                />
              </label>
              <label className="space-y-2 text-sm font-medium text-slate-300">
                Category
                <NativeSelect
                  value={draft.category}
                  onChange={(event) => page.updateSignDraft({ category: toSignCategory(event.target.value) })}
                >
                  {SIGN_LANGUAGE_CATEGORY_FILTERS
                    .filter((category) => category.value !== 'all')
                    .map((category) => (
                      <option key={category.value} value={category.value}>
                        {category.label}
                      </option>
                    ))}
                </NativeSelect>
              </label>
              <div className="lg:col-span-2">
                <SignAssetSection
                  title="Preview Image"
                  urlLabel="Image URL"
                  uploadLabel="Upload preview image"
                  value={draft.image}
                  placeholder="https://..."
                  uploadField="preview-images"
                  onChange={(value) => page.updateSignDraft({ image: value })}
                />
              </div>
              <div className="lg:col-span-2">
                <SignAssetSection
                  title="Animated GIF"
                  urlLabel="GIF URL"
                  uploadLabel="Upload GIF"
                  value={draft.gifUrl}
                  placeholder="https://..."
                  uploadField="gif-demos"
                  onChange={(value) => page.updateSignDraft({ gifUrl: value })}
                />
              </div>
              <label className="space-y-2 text-sm font-medium text-slate-300">
                YouTube Video URL
                <Input
                  value={draft.videoUrl}
                  onChange={(event) => updateTextField('videoUrl', event.target.value)}
                  placeholder="https://youtube.com/watch?v=..."
                />
              </label>
              <label className="space-y-2 text-sm font-medium text-slate-300">
                YouTube Search URL
                <Input
                  value={draft.youtubeSearchUrl}
                  onChange={(event) => updateTextField('youtubeSearchUrl', event.target.value)}
                  placeholder="https://youtube.com/results?search_query=..."
                />
              </label>
              <label className="space-y-2 text-sm font-medium text-slate-300 lg:col-span-2">
                Description
                <Textarea
                  value={draft.description}
                  onChange={(event) => updateTextField('description', event.target.value)}
                  placeholder="When and why staff should use this sign"
                />
              </label>
              <label className="space-y-2 text-sm font-medium text-slate-300 lg:col-span-2">
                Teaching Tip
                <Textarea
                  value={draft.tip}
                  onChange={(event) => updateTextField('tip', event.target.value)}
                  placeholder="Practical coaching detail"
                />
              </label>
            </div>

            <div className="mt-5 space-y-3">
              <div className="flex items-center justify-between gap-3">
                <h5 className="text-sm font-semibold text-slate-200">Step-by-Step Guide</h5>
                <Button type="button" variant="ghost" size="sm" onClick={page.addSignDraftStep}>
                  Add Step
                </Button>
              </div>
              {draft.videoSteps.map((step, index) => (
                <div key={step.step} className="grid gap-3 rounded-xl border border-slate-700/60 bg-slate-900/55 p-3 lg:grid-cols-[1fr_120px_auto]">
                  <Input
                    value={step.instruction}
                    onChange={(event) => page.updateSignDraftStep(index, { instruction: event.target.value })}
                    placeholder={`Step ${index + 1}`}
                  />
                  <Input
                    type="number"
                    min={1}
                    value={step.duration}
                    onChange={(event) => page.updateSignDraftStep(index, { duration: Number(event.target.value) })}
                    aria-label={`Step ${index + 1} duration`}
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => page.removeSignDraftStep(index)}
                    aria-label={`Remove step ${index + 1}`}
                    disabled={draft.videoSteps.length === 1}
                    className="text-red-300 hover:text-red-200"
                  >
                    <Trash2 size={16} />
                  </Button>
                </div>
              ))}
            </div>

            {page.signDraftError && (
              <p className="mt-4 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm font-medium text-red-300">
                {page.signDraftError}
              </p>
            )}

            <div className="mt-5 flex justify-end">
              <Button
                type="button"
                onClick={page.saveSignDraft}
                loading={page.isSavingSigns}
                leadingIcon={<Save size={16} />}
                className="bg-blue-600 hover:bg-blue-500 text-white"
              >
                Save Sign
              </Button>
            </div>
          </div>
        )}

        {Boolean(page.signManagementError) && (
          <p className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm font-medium text-red-300">
            Sign cards could not be saved.
          </p>
        )}
        {page.signSaveMessage && (
          <p className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm font-medium text-emerald-300">
            {page.signSaveMessage}
          </p>
        )}
      </div>
    </section>
  );
}
