'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardCategory, BoardPost } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';

export default function BoardEditPage() {
  const router = useRouter();
  const params = useParams();
  const postId = parseInt(params.id as string);
  const { user, isLoggedIn } = useAuthStore();
  const { translate, language } = useTranslate();

  const [post, setPost] = useState<BoardPost | null>(null);
  const [categories, setCategories] = useState<BoardCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [categoryId, setCategoryId] = useState<number | ''>('');
  const [isNotice, setIsNotice] = useState(false);
  const [isPinned, setIsPinned] = useState(false);

  useEffect(() => {
    if (!isLoggedIn) {
      router.push('/login?redirect=/board');
      return;
    }

    const fetchData = async () => {
      try {
        const [postData, categoriesRes] = await Promise.all([
          boardApi.getPost(postId),
          boardApi.getCategories(),
        ]);

        // Check permission
        if (postData.author_id !== user?.id && !user?.is_admin) {
          router.push('/board');
          return;
        }

        setPost(postData);
        setCategories(categoriesRes.categories);
        setTitle(postData.title);
        setContent(postData.content);
        setCategoryId(postData.category_id);
        setIsNotice(postData.is_notice);
        setIsPinned(postData.is_pinned);
      } catch (err: any) {
        setError(err.response?.data?.detail || 'Failed to load post');
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [isLoggedIn, postId, user, router]);

  const getCategoryName = (cat: BoardCategory) => {
    if (language === 'en' && cat.name_en) return cat.name_en;
    if (language === 'mn' && cat.name_mn) return cat.name_mn;
    if (language === 'ru' && cat.name_ru) return cat.name_ru;
    return cat.name;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!title.trim()) {
      setError(translate('Please enter a title'));
      return;
    }
    if (!content.trim()) {
      setError(translate('Please enter content'));
      return;
    }
    if (!categoryId) {
      setError(translate('Please select a category'));
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      await boardApi.updatePost(postId, {
        title: title.trim(),
        content: content.trim(),
        category_id: categoryId as number,
        is_notice: user?.is_admin ? isNotice : undefined,
        is_pinned: user?.is_admin ? isPinned : undefined,
      });
      router.push(`/board/${postId}`);
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to update post');
    } finally {
      setSubmitting(false);
    }
  };

  if (!isLoggedIn || loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
      </div>
    );
  }

  if (error && !post) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <Link href="/board" className="text-blue-600 hover:underline">
            {translate('Back to list')}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-4xl mx-auto px-4 py-8">
        {/* Back Button */}
        <div className="mb-6">
          <Link
            href={`/board/${postId}`}
            className="inline-flex items-center text-gray-600 hover:text-gray-900"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            {translate('Cancel')}
          </Link>
        </div>

        {/* Form */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="p-6 border-b border-gray-200">
            <h1 className="text-xl font-bold text-gray-900">
              {translate('Edit Post')}
            </h1>
          </div>

          <form onSubmit={handleSubmit} className="p-6 space-y-6">
            {error && (
              <div className="p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
                {error}
              </div>
            )}

            {/* Category */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                {translate('Category')} <span className="text-red-500">*</span>
              </label>
              <select
                value={categoryId}
                onChange={(e) => setCategoryId(e.target.value ? parseInt(e.target.value) : '')}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              >
                <option value="">{translate('Select a category')}</option>
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {getCategoryName(cat)}
                  </option>
                ))}
              </select>
            </div>

            {/* Title */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                {translate('Title')} <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder={translate('Enter title')}
                maxLength={200}
                required
              />
            </div>

            {/* Content */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                {translate('Content')} <span className="text-red-500">*</span>
              </label>
              <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[300px]"
                placeholder={translate('Enter content')}
                required
              />
            </div>

            {/* Admin Options */}
            {user?.is_admin && (
              <div className="space-y-3 p-4 bg-gray-50 rounded-lg">
                <h3 className="text-sm font-medium text-gray-700">{translate('Admin Options')}</h3>
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="isNotice"
                    checked={isNotice}
                    onChange={(e) => setIsNotice(e.target.checked)}
                    className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                  <label htmlFor="isNotice" className="text-sm text-gray-700">
                    {translate('Notice')}
                  </label>
                </div>
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="isPinned"
                    checked={isPinned}
                    onChange={(e) => setIsPinned(e.target.checked)}
                    className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                  <label htmlFor="isPinned" className="text-sm text-gray-700">
                    {translate('Pin to top')}
                  </label>
                </div>
              </div>
            )}

            {/* Submit Buttons */}
            <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
              <Link
                href={`/board/${postId}`}
                className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                {translate('Cancel')}
              </Link>
              <button
                type="submit"
                disabled={submitting}
                className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
              >
                {submitting ? translate('Saving...') : translate('Save')}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
