import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { ChevronLeft } from 'lucide-react'
import Button from '@/components/common/Button'
import Input from '@/components/common/Input'
import LoadingSpinner from '@/components/common/LoadingSpinner'
import { supabase } from '@/lib/supabase'
import { updateDatabook } from '@/lib/mutations'
import { toast } from '@/lib/toast'

export default function DatabookEdit() {
  const navigate = useNavigate()
  const { id } = useParams()
  const queryClient = useQueryClient()

  const [formData, setFormData] = useState({
    nome_projeto: '',
    numero_projeto: '',
    status: 'rascunho',
    progresso_percentual: 0,
  })
  
  const { data: projeto, isLoading: loadingProjeto } = useQuery({
    queryKey: ['projeto', id],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('projetos')
        .select('*, clientes(nome), databooks_mestres(*)')
        .eq('id', id)
        .single()
      
      if (error) throw error
      return data as any
    },
    enabled: !!id,
  })
  
  useEffect(() => {
    if (projeto) {
      setFormData({
        nome_projeto: projeto.nome_projeto,
        numero_projeto: projeto.numero_projeto,
        status: projeto.status,
        progresso_percentual: projeto.progresso_percentual,
      })
    }
  }, [projeto])
  
  const updateMutation = useMutation({
    mutationFn: () => updateDatabook(id!, {
      nome_projeto: formData.nome_projeto,
      status: formData.status,
      progresso_percentual: formData.progresso_percentual,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projetos'] })
      queryClient.invalidateQueries({ queryKey: ['projeto', id] })
      toast.success('Projeto atualizado com sucesso')
      navigate('/dashboard')
    },
    onError: () => {
      toast.error('Erro ao atualizar projeto')
    },
  })
  
  const handleSave = () => {
    updateMutation.mutate()
  }
  
  if (loadingProjeto) {
    return (
      <div className="flex items-center justify-center h-full">
        <LoadingSpinner size="lg" />
      </div>
    )
  }
  
  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" onClick={() => navigate('/dashboard')}>
          <ChevronLeft size={20} />
        </Button>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">Editar Projeto</h1>
      </div>
      
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label="Nome do Projeto"
              value={formData.nome_projeto}
              onChange={(e) => setFormData(prev => ({ ...prev, nome_projeto: e.target.value }))}
              required
            />
            <Input
              label="Número do Projeto"
              value={formData.numero_projeto}
              onChange={(e) => setFormData(prev => ({ ...prev, numero_projeto: e.target.value }))}
              required
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Progresso (%)
            </label>
            <input
              type="number"
              min="0"
              max="100"
              value={formData.progresso_percentual}
              onChange={(e) => setFormData(prev => ({ ...prev, progresso_percentual: parseInt(e.target.value) || 0 }))}
              className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
            />
          </div>
          
          {/* Botões de Status Sequencial */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
              Status do Projeto
            </label>
            <div className="flex flex-wrap gap-3">
              {/* Rascunho */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'rascunho' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'rascunho'
                    ? 'border-gray-400 bg-gray-400 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-gray-400'
                }`}
              >
                Rascunho
              </button>
              
              {/* Em Andamento */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'em_andamento' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'em_andamento'
                    ? 'border-blue-500 bg-blue-500 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-blue-500'
                }`}
              >
                Em Andamento
              </button>
              {/* Concluído */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'finalizado' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'finalizado'
                    ? 'border-green-500 bg-green-500 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-green-500'
                }`}
              >
                Concluído
              </button>
              
              {/* Em Revisão */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'revisao' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'revisao'
                    ? 'border-yellow-500 bg-yellow-500 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-yellow-500'
                }`}
              >
                Em Revisão
              </button>
              
              {/* Arquivado */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'arquivado' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'arquivado'
                    ? 'border-purple-500 bg-purple-500 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-purple-500'
                }`}
              >
                Arquivado
              </button>
              
              {/* Cancelado */}
              <button
                type="button"
                onClick={() => setFormData(prev => ({ ...prev, status: 'cancelado' }))}
                className={`px-4 py-2 rounded-lg border-2 transition-all font-medium ${
                  formData.status === 'cancelado'
                    ? 'border-red-500 bg-red-500 text-white'
                    : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:border-red-500'
                }`}
              >
                Cancelado
              </button>
            </div>
            
            {/* Indicador de Status Atual */}
            <div className="mt-3 text-sm text-gray-600 dark:text-gray-400">
              Status atual: <span className="font-semibold text-gray-900 dark:text-gray-100">
                {formData.status === 'rascunho' && 'Rascunho'}
                {formData.status === 'em_andamento' && 'Em Andamento'}
                {formData.status === 'finalizado' && 'Concluído'}
                {formData.status === 'revisao' && 'Em Revisão / Entregue'}
                {formData.status === 'arquivado' && 'Aceito / Arquivado'}
                {formData.status === 'cancelado' && 'Cancelado'}
              </span>
            </div>
          </div>
          
          {projeto?.databooks_mestres && (
            <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-2">
              <h3 className="font-semibold text-gray-900 dark:text-gray-100">Informações do Databook</h3>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <p className="text-gray-600 dark:text-gray-400">Cliente</p>
                  <p className="font-medium text-gray-900 dark:text-gray-100">{projeto.databooks_mestres.cliente_nome}</p>
                </div>
                <div>
                  <p className="text-gray-600 dark:text-gray-400">Produto</p>
                  <p className="font-medium text-gray-900 dark:text-gray-100">{projeto.databooks_mestres.produto_nome}</p>
                </div>
              </div>
            </div>
          )}
          
          <div className="flex justify-end gap-3">
            <Button
              variant="outline"
              onClick={() => navigate('/dashboard')}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleSave}
              isLoading={updateMutation.isPending}
            >
              Salvar Alterações
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
