'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Plus, X } from 'lucide-react';
import { Service, LocalizedString } from '@/types';
import Button from '@/components/ui/Button';
import Input, { Textarea, Select } from '@/components/ui/Input';
import ImageUploader from '@/components/ui/ImageUploader';
import LanguageTabs, { useLanguageTabs, Lang } from '@/components/ui/LanguageTabs';

interface ServiceFormProps {
  initialData?: Service;
  onSave: (data: Partial<Service>) => void;
  isSaving: boolean;
}

const emptyLS = (): LocalizedString => ({ en: '', zh: '' });

function asLS(val: unknown): LocalizedString {
  if (val && typeof val === 'object' && 'en' in val) return val as LocalizedString;
  if (typeof val === 'string') return { en: val, zh: '' };
  return emptyLS();
}

function asLSArray(val: unknown): LocalizedString[] {
  if (!Array.isArray(val)) return [];
  return val.map((v) => asLS(v));
}

export default function ServiceForm({ initialData, onSave, isSaving }: ServiceFormProps) {
  const { activeLang, setActiveLang } = useLanguageTabs();
  const [title, setTitle] = useState<LocalizedString>(asLS(initialData?.title));
  const [shortDescription, setShortDescription] = useState<LocalizedString>(asLS(initialData?.shortDescription));
  const [fullDescription, setFullDescription] = useState<LocalizedString>(asLS(initialData?.fullDescription));
  const [icon, setIcon] = useState(initialData?.icon ?? '');
  const [featuredImage, setFeaturedImage] = useState(initialData?.featuredImage ?? '');
  const [link, setLink] = useState(initialData?.link ?? '');
  const [features, setFeatures] = useState<LocalizedString[]>(asLSArray(initialData?.features));
  const [status, setStatus] = useState<Service['status']>(initialData?.status ?? 'active');
  const [newFeatureEn, setNewFeatureEn] = useState('');
  const [newFeatureZh, setNewFeatureZh] = useState('');

  const updateLS = (setter: React.Dispatch<React.SetStateAction<LocalizedString>>, lang: Lang, value: string) => {
    setter((prev) => ({ ...prev, [lang]: value }));
  };

  const addFeature = () => {
    if (newFeatureEn.trim() || newFeatureZh.trim()) {
      setFeatures([...features, { en: newFeatureEn.trim(), zh: newFeatureZh.trim() }]);
      setNewFeatureEn('');
      setNewFeatureZh('');
    }
  };

  const removeFeature = (idx: number) => {
    setFeatures(features.filter((_, i) => i !== idx));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      title,
      shortDescription,
      fullDescription,
      icon: icon || undefined,
      featuredImage: featuredImage || undefined,
      link: link || undefined,
      features,
      status,
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/services" className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg">
            <ArrowLeft size={18} />
          </Link>
          <h1 className="text-2xl font-bold text-gray-900">
            {initialData ? 'Edit Service' : 'New Service'}
          </h1>
        </div>
        <div className="flex items-center gap-3">
          <Select
            value={status}
            onChange={(e) => setStatus(e.target.value as Service['status'])}
            options={[
              { value: 'active', label: 'Active' },
              { value: 'inactive', label: 'Inactive' },
            ]}
            className="w-32"
          />
          <Button type="submit" isLoading={isSaving}>
            {initialData ? 'Save changes' : 'Create service'}
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
            <LanguageTabs activeLang={activeLang} onChange={setActiveLang} />

            <Input
              label={`Title (${activeLang.toUpperCase()})`}
              value={title[activeLang]}
              onChange={(e) => updateLS(setTitle, activeLang, e.target.value)}
              required={activeLang === 'en'}
              placeholder={activeLang === 'en' ? 'Service title' : '服務標題'}
            />
            <Textarea
              label={`Short Description (${activeLang.toUpperCase()})`}
              value={shortDescription[activeLang]}
              onChange={(e) => updateLS(setShortDescription, activeLang, e.target.value)}
              required={activeLang === 'en'}
              rows={2}
              placeholder={activeLang === 'en' ? 'Brief description (max 200 chars)' : '簡短描述（最多200字）'}
              maxLength={200}
              hint={`${shortDescription[activeLang].length}/200 characters`}
            />
            <Textarea
              label={`Full Description (${activeLang.toUpperCase()})`}
              value={fullDescription[activeLang]}
              onChange={(e) => updateLS(setFullDescription, activeLang, e.target.value)}
              required={activeLang === 'en'}
              rows={6}
              placeholder={activeLang === 'en' ? 'Detailed service description...' : '詳細服務描述...'}
            />
          </div>

          <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
            <h3 className="text-sm font-semibold text-gray-700">Features</h3>
            <div className="space-y-2">
              {features.map((feature, idx) => (
                <div key={idx} className="flex items-center gap-2">
                  <div className="w-1.5 h-1.5 rounded-full bg-blue-500 flex-shrink-0" />
                  <span className="flex-1 text-sm text-gray-700">
                    {feature.en}{feature.zh ? ` / ${feature.zh}` : ''}
                  </span>
                  <button type="button" onClick={() => removeFeature(idx)} className="text-gray-400 hover:text-red-500 p-0.5">
                    <X size={14} />
                  </button>
                </div>
              ))}
            </div>
            <div className="space-y-2">
              <div className="flex gap-2">
                <input
                  type="text"
                  value={newFeatureEn}
                  onChange={(e) => setNewFeatureEn(e.target.value)}
                  placeholder="Feature (EN)"
                  className="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <input
                  type="text"
                  value={newFeatureZh}
                  onChange={(e) => setNewFeatureZh(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addFeature(); } }}
                  placeholder="功能 (ZH)"
                  className="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <Button type="button" variant="secondary" size="sm" onClick={addFeature}>
                <Plus size={14} />
                Add
              </Button>
            </div>
          </div>
        </div>

        <div className="space-y-5">
          <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
            <Input
              label="Link URL"
              value={link}
              onChange={(e) => setLink(e.target.value)}
              placeholder="/services/golf-academy"
              hint="Leave blank to use the default service detail page"
            />
            <Input
              label="Icon name"
              value={icon}
              onChange={(e) => setIcon(e.target.value)}
              placeholder="e.g. star, globe, chart"
              hint="Icon identifier for the frontend"
            />
            <ImageUploader
              label="Featured Image"
              value={featuredImage}
              onChange={setFeaturedImage}
            />
          </div>
        </div>
      </div>
    </form>
  );
}
