import { Languages } from 'lucide-react';
import { createContext, useContext, useState } from 'react';
import type { ReactNode } from 'react';
import RichTextEditor from '@/components/rich-text-editor';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { cn } from '@/lib/utils';

export type LocaleOption = { value: string; label: string };

/**
 * Daftar bahasa default — urutan pertama = tab default (aktif di awal).
 * Dinamis: cukup ganti prop `locales` pada TranslationCard/FormLanguageTabs.
 */
export const DEFAULT_LOCALES: LocaleOption[] = [
    { value: 'id', label: 'Indonesia' },
    { value: 'en', label: 'English' },
];

const LocaleContext = createContext<string>('id');

/**
 * Bahasa aktif dari tab TranslationCard/FormLanguageTabs — dipakai TranslatableField.
 */
export function useLocaleField(): string {
    return useContext(LocaleContext);
}

type LanguageTabsProps = {
    locales?: LocaleOption[];
    defaultLocale?: string;
    children: ReactNode;
};

/**
 * Tab bahasa (mis. Indonesia | English) + provider locale aktif.
 *
 * Berbeda dari LocaleTabs lama (toggle per field): SATU tab mengontrol SEMUA
 * field translatable di dalamnya — pengguna mengisi satu bahasa, lalu pindah tab.
 * Nilai kedua bahasa tetap dipegang react-hook-form (object { id, en }).
 */
export function FormLanguageTabs({
    locales = DEFAULT_LOCALES,
    defaultLocale,
    children,
}: LanguageTabsProps) {
    const [active, setActive] = useState(
        defaultLocale ?? locales[0]?.value ?? 'id',
    );

    return (
        <div className="space-y-6">
            <Tabs value={active} onValueChange={setActive}>
                <TabsList aria-label="Bahasa konten">
                    {locales.map((locale) => (
                        <TabsTrigger key={locale.value} value={locale.value}>
                            {locale.label}
                        </TabsTrigger>
                    ))}
                </TabsList>
            </Tabs>

            <LocaleContext.Provider value={active}>
                {children}
            </LocaleContext.Provider>
        </div>
    );
}

type TranslatableFieldProps = {
    label: string;
    required?: boolean;
    value: Record<string, string>;
    onChange: (value: Record<string, string>) => void;
    type?: 'input' | 'textarea' | 'richtext';
    placeholder?: string;
    hint?: string;
    error?: string;
};

/**
 * Field translatable — render input/textarea/richtext untuk bahasa aktif saja.
 * RichTextEditor di-remount (key=locale) agar konten editor mengikuti tab.
 */
export function TranslatableField({
    label,
    required = false,
    value,
    onChange,
    type = 'input',
    placeholder,
    hint,
    error,
}: TranslatableFieldProps) {
    const locale = useLocaleField();

    const update = (next: string) => onChange({ ...value, [locale]: next });

    return (
        <div className="space-y-2">
            <Label className="flex items-center gap-1.5">
                <Languages className="size-3.5 text-muted-foreground" />
                {label}
                {required && (
                    <span aria-label="Wajib diisi" className="text-destructive">
                        *
                    </span>
                )}
            </Label>

            {type === 'richtext' ? (
                <RichTextEditor
                    key={locale}
                    locale={locale}
                    value={value[locale] ?? ''}
                    onChange={update}
                    placeholder={placeholder}
                />
            ) : type === 'textarea' ? (
                <Textarea
                    rows={4}
                    value={value[locale] ?? ''}
                    onChange={(event) => update(event.target.value)}
                    placeholder={placeholder}
                />
            ) : (
                <Input
                    value={value[locale] ?? ''}
                    onChange={(event) => update(event.target.value)}
                    placeholder={placeholder}
                />
            )}

            {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
            {error && <p className="text-sm text-destructive">{error}</p>}
        </div>
    );
}

type TranslationCardProps = LanguageTabsProps & {
    title: string;
    description?: string;
};

/**
 * Card konten translatable — tab bahasa di atas, field translatable di bawahnya.
 * Dipakai di halaman create/edit (best practice: satu card per bagian form).
 */
export function TranslationCard({
    title,
    description,
    locales,
    defaultLocale,
    children,
}: TranslationCardProps) {
    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <Languages className="size-4 text-muted-foreground" />
                    {title}
                </CardTitle>
                {description && (
                    <CardDescription>{description}</CardDescription>
                )}
            </CardHeader>
            <CardContent>
                <FormLanguageTabs
                    locales={locales}
                    defaultLocale={defaultLocale}
                >
                    {children}
                </FormLanguageTabs>
            </CardContent>
        </Card>
    );
}

/**
 * Card untuk bagian non-translatable (media, pengaturan: urutan/status/dll.) —
 * dipisah dari card translation sesuai best practice form.
 */
export function FormSection({
    title,
    description,
    children,
}: {
    title: string;
    description?: string;
    children: ReactNode;
}) {
    return (
        <Card>
            <CardHeader>
                <CardTitle className="text-lg">{title}</CardTitle>
                {description && (
                    <CardDescription>{description}</CardDescription>
                )}
            </CardHeader>
            <CardContent className="space-y-6">{children}</CardContent>
        </Card>
    );
}

type FormSwitchProps = {
    label: string;
    description?: string;
    checked: boolean;
    onCheckedChange: (checked: boolean) => void;
    name?: string;
    boxed?: boolean;
    showLabel?: boolean;
};

/**
 * Switch kompak (label + toggle) untuk status aktif/nonaktif — baris ramping,
 * tidak memenuhi lebar card (perbaikan UI/UX Sesi 37).
 */
export function FormSwitch({
    label,
    description,
    checked,
    onCheckedChange,
    name,
    boxed = true,
    showLabel = true,
}: FormSwitchProps) {
    return (
        <div
            className={cn(
                'flex items-center justify-between gap-4',
                boxed && 'w-fit rounded-lg border px-4 py-3 sm:max-w-md',
            )}
        >
            {showLabel && (
                <div>
                    <Label className="font-medium">{label}</Label>
                    {description && (
                        <p className="text-sm text-muted-foreground">
                            {description}
                        </p>
                    )}
                </div>
            )}
            <Switch
                checked={checked}
                onCheckedChange={onCheckedChange}
                aria-label={name ?? label}
            />
        </div>
    );
}
