"use client";

import { useRef, useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useToast } from '@/contexts/ToastContext';

type UploadedImage = {
  url: string;
  path: string;
  name: string;
};

const CATEGORY_OPTIONS = [
  { value: 'Engenharia Veicular', label: 'Engenharia Veicular' },
  { value: 'Projetos Mecânicos', label: 'Projetos Mecânicos' },
  { value: 'Laudos e Inspeções', label: 'Laudos e Inspeções' },
  { value: 'Segurança do Trabalho', label: 'Segurança do Trabalho' },
];

const STATUS_OPTIONS = [
  { value: 'Concluído', label: 'Concluído' },
  { value: 'Em andamento', label: 'Em andamento' },
  { value: 'Rascunho', label: 'Rascunho' },
];

export default function EditProject({ params }: { params: { id: string } }) {
  const router = useRouter();
  const { success, error } = useToast();
  const coverInputRef = useRef<HTMLInputElement | null>(null);
  const galleryInputRef = useRef<HTMLInputElement | null>(null);
  const [loadingData, setLoadingData] = useState(true);
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState(CATEGORY_OPTIONS);
  const [newCategory, setNewCategory] = useState('');
  const [formData, setFormData] = useState({
    title: '',
    category: '',
    client: '',
    status: 'Concluído',
    description: '',
    date: '',
    featured: false,
  });
  const [coverImage, setCoverImage] = useState<UploadedImage | null>(null);
  const [galleryImages, setGalleryImages] = useState<UploadedImage[]>([]);
  const [uploadingCover, setUploadingCover] = useState(false);
  const [uploadingGallery, setUploadingGallery] = useState(false);

  const isSaving = loading || uploadingCover || uploadingGallery;

  // Carregar dados do projeto
  useEffect(() => {
    async function fetchProject() {
      try {
        const res = await fetch(`/api/projects/${params.id}`);
        if (!res.ok) {
          throw new Error('Projeto não encontrado');
        }
        const project = await res.json();
        
        setFormData({
          title: project.title || '',
          category: project.category || '',
          client: project.client || '',
          status: project.status || 'Concluído',
          description: project.description || '',
          date: project.completionDate ? project.completionDate.split('T')[0] : '',
          featured: project.featured || false,
        });

        if (project.coverImage) {
          setCoverImage({
            url: project.coverImage,
            path: project.coverImage,
            name: 'Imagem de capa',
          });
        }

        if (project.galleryImages && project.galleryImages.length > 0) {
          setGalleryImages(
            project.galleryImages.map((url: string, index: number) => ({
              url,
              path: url,
              name: `Imagem ${index + 1}`,
            }))
          );
        }
      } catch (err) {
        console.error('Erro ao carregar projeto:', err);
        error('Não foi possível carregar o projeto.');
        router.push('/admin/projetos');
      } finally {
        setLoadingData(false);
      }
    }
    fetchProject();
  }, [params.id, error, router]);

  const uploadFile = async (file: File): Promise<UploadedImage | null> => {
    if (file.size > 2 * 1024 * 1024) {
      error('Arquivo maior que 2MB. Escolha uma imagem menor.');
      return null;
    }

    const supportedTypes = ['image/png', 'image/jpeg', 'image/webp'];
    if (!supportedTypes.includes(file.type)) {
      error('Formato inválido. Utilize PNG, JPG ou WEBP.');
      return null;
    }

    const body = new FormData();
    body.append('file', file);

    const response = await fetch('/api/upload', {
      method: 'POST',
      body,
    });

    if (!response.ok) {
      const data = await response.json().catch(() => ({}));
      throw new Error(data?.error || 'Erro ao enviar imagem');
    }

    const data = await response.json();
    return {
      url: data.url,
      path: data.path,
      name: file.name,
    };
  };

  const handleCoverSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setUploadingCover(true);
    try {
      const uploaded = await uploadFile(file);
      if (uploaded) {
        setCoverImage(uploaded);
        success('Imagem de capa carregada.');
      }
    } catch (err) {
      console.error('Erro ao enviar imagem de capa:', err);
      error(err instanceof Error ? err.message : 'Falha ao enviar imagem de capa.');
    } finally {
      setUploadingCover(false);
      event.target.value = '';
    }
  };

  const handleGallerySelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files ?? []);
    if (files.length === 0) return;

    if (galleryImages.length + files.length > 8) {
      error('Limite de 8 imagens atingido. Remova algumas antes de adicionar novas.');
      event.target.value = '';
      return;
    }

    setUploadingGallery(true);
    try {
      for (const file of files) {
        const uploaded = await uploadFile(file);
        if (uploaded) {
          setGalleryImages((prev) => [...prev, uploaded]);
        }
      }
      success('Galeria atualizada.');
    } catch (err) {
      console.error('Erro ao enviar imagem da galeria:', err);
      error(err instanceof Error ? err.message : 'Falha ao enviar imagem da galeria.');
    } finally {
      setUploadingGallery(false);
      event.target.value = '';
    }
  };

  const handleRemoveGalleryImage = (path: string) => {
    setGalleryImages((prev) => prev.filter((image) => image.path !== path));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.title || !formData.category) {
      error('Informe ao menos o título e a categoria do projeto.');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`/api/projects/${params.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: formData.title.trim(),
          category: formData.category,
          client: formData.client?.trim() || null,
          status: formData.status,
          description: formData.description?.trim() || null,
          completionDate: formData.date ? new Date(formData.date).toISOString() : null,
          coverImage: coverImage?.url ?? null,
          galleryImages: galleryImages.map((image) => image.url),
          featured: formData.featured,
        }),
      });

      const data = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(data?.error || 'Erro ao atualizar projeto');
      }

      success('Projeto atualizado com sucesso!');
      router.push('/admin/projetos');
    } catch (err) {
      console.error('Erro ao atualizar projeto:', err);
      error(err instanceof Error ? err.message : 'Não foi possível atualizar o projeto.');
    } finally {
      setLoading(false);
    }
  };

  if (loadingData) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-center py-20">
          <i className="ri-loader-4-line animate-spin text-4xl text-primary"></i>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      <div className="flex items-center gap-4 mb-8">
        <Link 
          href="/admin/projetos" 
          className="w-10 h-10 rounded-xl bg-white dark:bg-secondary border border-gray-200 dark:border-white/10 flex items-center justify-center text-gray-500 hover:text-primary hover:border-primary transition-colors shadow-sm"
        >
          <i className="ri-arrow-left-line text-xl"></i>
        </Link>
        <div>
          <h1 className="text-3xl font-bold font-headline text-secondary dark:text-white mb-1">Editar Projeto</h1>
          <p className="text-gray-500 dark:text-gray-400">Atualize as informações do projeto.</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-8">
        {/* Basic Info */}
        <div className="bg-white dark:bg-secondary p-8 rounded-2xl border border-gray-200 dark:border-white/10 shadow-sm">
          <h2 className="text-xl font-bold text-secondary dark:text-white mb-6 flex items-center gap-2">
            <i className="ri-information-line text-primary"></i>
            Informações Básicas
          </h2>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="md:col-span-2">
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Título do Projeto</label>
              <input 
                type="text" 
                value={formData.title}
                onChange={(e) => setFormData({...formData, title: e.target.value})}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
                placeholder="Ex: Adequação de Frota Coca-Cola"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Categoria</label>
              <select 
                value={formData.category}
                onChange={(e) => setFormData({...formData, category: e.target.value})}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all appearance-none cursor-pointer"
                required
              >
                <option value="">Selecione uma categoria</option>
                {categories.map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Não encontra a categoria? Adicione uma nova abaixo</p>
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Adicionar Nova Categoria</label>
              <div className="flex gap-2">
                <input 
                  type="text" 
                  value={newCategory}
                  onChange={(e) => setNewCategory(e.target.value)}
                  className="flex-1 px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
                  placeholder="Ex: Consultoria Ambiental"
                />
                <button
                  type="button"
                  onClick={() => {
                    if (newCategory.trim()) {
                      const newCat = { value: newCategory, label: newCategory };
                      setCategories([...categories, newCat]);
                      setFormData({...formData, category: newCategory});
                      setNewCategory('');
                      success('Categoria adicionada!');
                    }
                  }}
                  className="px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary/90 transition-colors whitespace-nowrap"
                >
                  Adicionar
                </button>
              </div>
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Cliente</label>
              <input 
                type="text" 
                value={formData.client}
                onChange={(e) => setFormData({...formData, client: e.target.value})}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
                placeholder="Ex: Coca-Cola FEMSA"
              />
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Data de Conclusão</label>
              <input 
                type="date" 
                value={formData.date}
                onChange={(e) => setFormData({...formData, date: e.target.value})}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
              />
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Status</label>
              <select 
                value={formData.status}
                onChange={(e) => setFormData({...formData, status: e.target.value})}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all appearance-none cursor-pointer"
              >
                {STATUS_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </div>

            <div className="md:col-span-2">
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Descrição Detalhada</label>
              <textarea 
                value={formData.description}
                onChange={(e) => setFormData({...formData, description: e.target.value})}
                rows={6}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10 rounded-xl text-gray-900 dark:text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all resize-none"
                placeholder="Descreva os detalhes técnicos, desafios e soluções do projeto..."
              ></textarea>
            </div>

            <div className="md:col-span-2">
              <label className="flex items-center gap-3 text-sm font-bold text-gray-700 dark:text-gray-300">
                <input
                  type="checkbox"
                  checked={formData.featured}
                  onChange={(e) => setFormData({ ...formData, featured: e.target.checked })}
                  className="h-5 w-5 rounded border-gray-300 text-primary focus:ring-primary"
                />
                Destacar este projeto no site
              </label>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Projetos em destaque podem ser exibidos em seções especiais como a home.</p>
            </div>
          </div>
        </div>

        {/* Media */}
        <div className="bg-white dark:bg-secondary p-8 rounded-2xl border border-gray-200 dark:border-white/10 shadow-sm">
          <h2 className="text-xl font-bold text-secondary dark:text-white mb-6 flex items-center gap-2">
            <i className="ri-image-line text-primary"></i>
            Mídia
          </h2>

          <div className="space-y-6">
            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Imagem de Capa</label>
              <div
                onClick={() => coverInputRef.current?.click()}
                className="border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl p-6 text-center hover:border-primary dark:hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5 relative min-h-[200px] flex items-center justify-center"
              >
                {coverImage ? (
                  <div className="w-full h-full relative">
                    <img src={coverImage.url} alt={coverImage.name} className="w-full h-full object-cover rounded-lg" />
                    <button
                      type="button"
                      onClick={(event) => {
                        event.stopPropagation();
                        setCoverImage(null);
                      }}
                      className="absolute top-3 right-3 bg-black/60 text-white w-8 h-8 rounded-full flex items-center justify-center hover:bg-black/80 transition-colors"
                    >
                      <i className="ri-close-line"></i>
                    </button>
                  </div>
                ) : (
                  <div className="flex flex-col items-center">
                    <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center text-primary mb-4">
                      {uploadingCover ? (
                        <i className="ri-loader-4-line text-3xl animate-spin"></i>
                      ) : (
                        <i className="ri-upload-cloud-2-line text-3xl"></i>
                      )}
                    </div>
                    <p className="text-gray-600 dark:text-gray-300 font-medium mb-1">
                      {uploadingCover ? 'Enviando imagem...' : 'Clique para fazer upload ou arraste e solte'}
                    </p>
                    <p className="text-xs text-gray-400">PNG, JPG ou WEBP (máximo 2MB)</p>
                  </div>
                )}
                <input
                  ref={coverInputRef}
                  type="file"
                  accept="image/png,image/jpeg,image/webp"
                  className="hidden"
                  onChange={handleCoverSelect}
                  disabled={uploadingCover}
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">Galeria de Fotos</label>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <button
                  type="button"
                  onClick={() => galleryInputRef.current?.click()}
                  className="aspect-square border-2 border-dashed border-gray-300 dark:border-white/20 rounded-xl flex flex-col items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-colors cursor-pointer bg-gray-50 dark:bg-white/5"
                  disabled={uploadingGallery}
                >
                  {uploadingGallery ? (
                    <>
                      <i className="ri-loader-4-line text-3xl mb-2 animate-spin"></i>
                      <span className="text-xs font-bold">Enviando...</span>
                    </>
                  ) : (
                    <>
                      <i className="ri-add-line text-3xl mb-2"></i>
                      <span className="text-xs font-bold">Adicionar</span>
                    </>
                  )}
                </button>

                {galleryImages.map((image) => (
                  <div key={image.path} className="aspect-square rounded-xl bg-gray-200 dark:bg-white/10 relative group overflow-hidden">
                    <img src={image.url} alt={image.name} className="w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                      <button
                        type="button"
                        onClick={() => handleRemoveGalleryImage(image.path)}
                        className="w-9 h-9 rounded-lg bg-white/20 hover:bg-white/40 text-white flex items-center justify-center backdrop-blur-sm transition-colors"
                      >
                        <i className="ri-delete-bin-line"></i>
                      </button>
                    </div>
                  </div>
                ))}
                <input
                  ref={galleryInputRef}
                  type="file"
                  accept="image/png,image/jpeg,image/webp"
                  multiple
                  className="hidden"
                  onChange={handleGallerySelect}
                  disabled={uploadingGallery}
                />
              </div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Adicione até 8 imagens para apresentar detalhes do projeto.</p>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center justify-end gap-4 pt-4">
          <Link 
            href="/admin/projetos"
            className="px-8 py-3 border border-gray-200 dark:border-white/10 text-gray-600 dark:text-gray-300 rounded-xl font-bold hover:bg-gray-50 dark:hover:bg-white/5 transition-colors"
          >
            Cancelar
          </Link>
          <button 
            type="submit" 
            disabled={isSaving}
            className="px-8 py-3 bg-primary text-white rounded-xl font-bold hover-primary transition-colors shadow-lg shadow-primary/20 flex items-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
          >
            {isSaving ? (
              <>
                <i className="ri-loader-4-line animate-spin"></i>
                Salvando...
              </>
            ) : (
              <>
                <i className="ri-save-line"></i>
                Atualizar Projeto
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
