import React, { useState, useEffect } from "react";
import { useAuth } from "../contexts/AuthContext";
import { useData } from "../contexts/DataContext";
import { UserRole } from "../types";
import { Button } from "../components/Button";
import { getCadastroFot, deleteCadastroFot, checkFotHasEvents } from "../services/apiService";
import { Briefcase, AlertTriangle, Plus, Edit, Trash2, Search, Filter } from "lucide-react";
import { FotForm } from "../components/FotForm";

interface FotData {
  id: string;
  fot: number;
  empresa_nome: string;
  curso_nome: string;
  observacoes: string;
  instituicao: string;
  ano_formatura_label: string;
  cidade: string;
  estado: string;
  gastos_captacao: number;
  pre_venda: boolean;
  empresa_id?: string;
  curso_id?: string;
  ano_formatura_id?: string;
}

export const CourseManagement: React.FC = () => {
  const { user } = useAuth();
  const { events } = useData();
  const [fotList, setFotList] = useState<FotData[]>([]);
  const [filteredList, setFilteredList] = useState<FotData[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Modal State
  const [showForm, setShowForm] = useState(false);
  const [editingFot, setEditingFot] = useState<FotData | null>(null);

  // Filter State
  const [searchTerm, setSearchTerm] = useState("");

  // Verificar se è admin
  const isAdmin =
    user?.role === UserRole.SUPERADMIN ||
    user?.role === UserRole.BUSINESS_OWNER;

  useEffect(() => {
    fetchFotData();
  }, [isAdmin]);

  useEffect(() => {
    if (searchTerm.trim() === "") {
      setFilteredList(fotList);
    } else {
      const lowerTerm = searchTerm.toLowerCase();
      const filtered = fotList.filter(item =>
        item.fot.toString().includes(lowerTerm) ||
        (item.empresa_nome || "").toLowerCase().includes(lowerTerm) ||
        (item.curso_nome || "").toLowerCase().includes(lowerTerm) ||
        (item.instituicao || "").toLowerCase().includes(lowerTerm)
      );
      setFilteredList(filtered);
    }
  }, [searchTerm, fotList]);

  const fetchFotData = async () => {
    if (!isAdmin) return;

    const token = localStorage.getItem("token");
    if (!token) return;

    try {
      setIsLoading(true);
      const response = await getCadastroFot(token);
      if (response.data) {
        setFotList(response.data);
        setError(null);
      } else if (response.error) {
        setError(response.error);
      }
    } catch (err) {
      console.error(err);
      setError("Erro ao carregar dados.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleFormSubmit = () => {
    setShowForm(false);
    setEditingFot(null);
    fetchFotData(); // Refresh list after successful creation/update
  };

  const handleEdit = (item: FotData) => {
    setEditingFot(item);
    setShowForm(true);
  };

  const handleDelete = async (id: string, fotNumber: number) => {
    const token = localStorage.getItem("token");
    if (!token) return;

    try {
      // Primeiro, verificar se há eventos associados ao FOT
      // Verificação local usando os eventos do DataContext
      const associatedEvents = events.filter(event => 
        event.fotId === id || 
        (typeof event.fot === 'number' && event.fot === fotNumber)
      );

      if (associatedEvents.length > 0) {
        alert(
          `Não é possível excluir este FOT pois existem ${associatedEvents.length} evento(s) associado(s) a ele.\n\n` +
          `Eventos associados:\n${associatedEvents.map(e => `- ${e.name} (${new Date(e.date + "T00:00:00").toLocaleDateString("pt-BR")})`).join('\n')}`
        );
        return;
      }

      // Tentar verificação adicional via API se disponível
      try {
        const checkResult = await checkFotHasEvents(id, token);
        if (checkResult.data?.hasEvents) {
          alert(
            `Não é possível excluir este FOT pois existem ${checkResult.data.eventCount} evento(s) associado(s) a ele no sistema.`
          );
          return;
        }
      } catch (apiError) {
        // Se a API não estiver disponível, continua com a verificação local
        console.log("API check not available, using local verification");
      }

      // Se chegou até aqui, não há eventos associados
      if (!window.confirm(`Tem certeza que deseja excluir o FOT ${fotNumber}?`)) return;

      const res = await deleteCadastroFot(id, token);
      if (res.error) {
        alert(res.error);
      } else {
        fetchFotData();
      }
    } catch (err) {
      console.error(err);
      alert("Erro ao excluir.");
    }
  };

  // Extract existing FOT numbers for uniqueness validation
  const existingFots = fotList.map(item => item.fot);

  // Drag scroll logic
  const tableContainerRef = React.useRef<HTMLDivElement>(null);
  const topScrollRef = React.useRef<HTMLDivElement>(null); // Ref for top scrollbar
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);
  const [tableScrollWidth, setTableScrollWidth] = useState(0);

  // Update top scrollbar width when data changes
  React.useEffect(() => {
    if (tableContainerRef.current) {
      setTableScrollWidth(tableContainerRef.current.scrollWidth);
    }
  }, [filteredList, isLoading]);

  // Sync scroll handlers
  const handleTableScroll = () => {
    if (tableContainerRef.current && topScrollRef.current) {
        if (topScrollRef.current.scrollLeft !== tableContainerRef.current.scrollLeft) {
            topScrollRef.current.scrollLeft = tableContainerRef.current.scrollLeft;
        }
    }
  };

  const handleTopScroll = () => {
    if (tableContainerRef.current && topScrollRef.current) {
        if (tableContainerRef.current.scrollLeft !== topScrollRef.current.scrollLeft) {
            tableContainerRef.current.scrollLeft = topScrollRef.current.scrollLeft;
        }
    }
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    if (!tableContainerRef.current) return;
    setIsDragging(true);
    setStartX(e.pageX - tableContainerRef.current.offsetLeft);
    setScrollLeft(tableContainerRef.current.scrollLeft);
  };

  const handleMouseLeave = () => {
    setIsDragging(false);
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !tableContainerRef.current) return;
    e.preventDefault();
    const x = e.pageX - tableContainerRef.current.offsetLeft;
    const walk = (x - startX) * 2; // Scroll-fast
    tableContainerRef.current.scrollLeft = scrollLeft - walk;
  };

  if (!isAdmin) {
    return (
      <div className="min-h-screen bg-gray-50 pt-32 pb-12">
        <div className="max-w-7xl mx-auto px-4 text-center">
          <h1 className="text-2xl font-bold text-red-600">Acesso Negado</h1>
          <p className="text-gray-600 mt-2">
            Apenas administradores podem acessar esta página.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-20 sm:pt-24 md:pt-28 lg:pt-32 pb-8 sm:pb-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="mb-6 sm:mb-8">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
            <div>
              <h1 className="text-2xl sm:text-3xl font-serif font-bold text-brand-black">
                Gestão de FOT
              </h1>
              <p className="text-sm sm:text-base text-gray-600 mt-1">
                Gerencie todas as turmas FOT cadastradas
              </p>
            </div>
            <Button
              onClick={() => {
                setEditingFot(null);
                setShowForm(true);
              }}
              variant="secondary"
              className="flex items-center space-x-2"
            >
              <Plus size={16} />
              <span>Cadastro FOT</span>
            </Button>
          </div>

          {/* Filters Bar */}
          <div className="bg-white p-4 rounded-lg border border-gray-200 shadow-sm flex items-center justify-between gap-4 flex-wrap">
            <div className="relative flex-1 max-w-md min-w-[200px]">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              <input
                type="text"
                placeholder="Buscar por FOT, Empresa, Curso..."
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-brand-gold focus:border-transparent"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
             <span className="text-sm font-semibold bg-gray-100 px-3 py-1 rounded-full text-gray-700">
               Total: {filteredList.length}
             </span>
          </div>
        </div>

        {/* Form Modal */}
        {showForm && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <FotForm
              onCancel={() => {
                setShowForm(false);
                setEditingFot(null);
              }}
              onSubmit={handleFormSubmit}
              token={localStorage.getItem("token") || ""}
              existingFots={existingFots}
              initialData={editingFot}
            />
          </div>
        )}

        {/* Error State */}
        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center gap-3 text-red-700">
            <AlertTriangle size={20} />
            <p>{error}</p>
          </div>
        )}

        {/* Courses Table */}
        <div className="bg-white rounded-lg shadow border border-gray-200 overflow-hidden flex flex-col">
          {isLoading ? (
            <div className="p-12 text-center text-gray-500">
              Carregando dados...
            </div>
          ) : (
            <>
              {/* Mobile List View */}
              <div className="md:hidden divide-y divide-gray-100">
                {filteredList.length === 0 ? (
                  <div className="p-8 text-center text-gray-500">
                    <Briefcase className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                    <p className="text-lg font-medium">Nenhuma turma FOT encontrada</p>
                  </div>
                ) : (
                  filteredList.map((item) => (
                    <div key={item.id} className="p-4 bg-white hover:bg-gray-50 transition-colors">
                      <div className="flex justify-between items-start mb-2">
                        <div>
                          <span className="font-bold text-gray-900 text-lg block">FOT {item.fot}</span>
                          <div className="text-sm font-medium text-gray-700">{item.empresa_nome}</div>
                        </div>
                        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${item.pre_venda ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"}`}>
                          {item.pre_venda ? "Pré-venda" : "Regular"}
                        </span>
                      </div>

                      <div className="space-y-1 mb-3 bg-gray-50 p-3 rounded-lg border border-gray-100">
                        <p className="text-sm"><span className="font-semibold text-gray-500 w-20 inline-block">Curso:</span> {item.curso_nome}</p>
                        <p className="text-sm"><span className="font-semibold text-gray-500 w-20 inline-block">Inst:</span> {item.instituicao}</p>
                        <p className="text-sm flex items-center gap-1 text-gray-600 mt-1 pt-1 border-t border-gray-200">
                          {item.cidade} - {item.estado}
                          <span className="mx-1">•</span>
                          {item.ano_formatura_label}
                        </p>
                      </div>

                      {item.observacoes && (
                        <p className="text-xs text-gray-500 italic mb-3 pl-2 border-l-2 border-brand-gold/30">
                          {item.observacoes}
                        </p>
                      )}

                      <div className="flex items-center justify-between mt-3">
                        <div className="text-sm font-bold text-gray-900 bg-green-50 px-2 py-1 rounded border border-green-100">
                          {item.gastos_captacao ? item.gastos_captacao.toLocaleString("pt-BR", { style: "currency", currency: "BRL" }) : "R$ 0,00"}
                        </div>
                        <div className="flex gap-2">
                          <button
                            onClick={() => handleEdit(item)}
                            className="flex items-center gap-1 px-3 py-1.5 text-blue-700 bg-blue-50 border border-blue-100 rounded-lg text-sm font-medium hover:bg-blue-100"
                          >
                            <Edit size={16} /> Editar
                          </button>
                          <button
                            onClick={() => handleDelete(item.id, item.fot)}
                            className="flex items-center gap-1 px-3 py-1.5 text-red-700 bg-red-50 border border-red-100 rounded-lg text-sm font-medium hover:bg-red-100"
                          >
                            <Trash2 size={16} /> Excluir
                          </button>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>

              {/* Top Scrollbar (Desktop) */}
              <div 
                ref={topScrollRef} 
                className="hidden md:block overflow-x-auto border-b border-gray-200 bg-gray-50 mb-1"
                onScroll={handleTopScroll}
                style={{ minHeight: '12px' }}
              >
                  <div style={{ width: tableScrollWidth > 0 ? tableScrollWidth : '100%', height: '1px' }}></div>
              </div>

              <div 
                ref={tableContainerRef}
                className={`hidden md:block overflow-x-auto ${isDragging ? 'cursor-grabbing' : 'cursor-grab'}`}
                onMouseDown={handleMouseDown}
                onMouseLeave={handleMouseLeave}
                onMouseUp={handleMouseUp}
                onMouseMove={handleMouseMove}
                onScroll={handleTableScroll}
              >
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50 select-none">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        FOT
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Empresa
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Curso
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Instituição
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Ano Formatura
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Cidade
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Estado
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Observações
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Gastos Captação
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Pré Venda
                      </th>
                      <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Ações
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {filteredList.length === 0 ? (
                      <tr>
                        <td
                          colSpan={11}
                          className="px-6 py-12 text-center text-gray-500"
                        >
                          <div className="flex flex-col items-center justify-center">
                            <Briefcase className="w-12 h-12 text-gray-300 mb-3" />
                            <p className="text-lg font-medium">
                              Nenhuma turma FOT encontrada
                            </p>
                          </div>
                        </td>
                      </tr>
                    ) : (
                      filteredList.map((item) => (
                        <tr
                          key={item.id}
                          className="hover:bg-gray-50 transition-colors"
                        >
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <div className="text-sm font-medium text-gray-900">
                                {item.fot || "-"}
                              </div>
                              {(() => {
                                const hasEvents = events.some(event => 
                                  event.fotId === item.id || 
                                  (typeof event.fot === 'number' && event.fot === item.fot)
                                );
                                return hasEvents && (
                                  <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    Com eventos
                                  </span>
                                );
                              })()}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.empresa_nome || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.curso_nome || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.instituicao || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.ano_formatura_label || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.cidade || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.estado || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <div className="text-sm text-gray-600 max-w-xs truncate" title={item.observacoes}>
                              {item.observacoes || "-"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <div className="text-sm text-gray-600">
                              {item.gastos_captacao
                                ? item.gastos_captacao.toLocaleString("pt-BR", {
                                  style: "currency",
                                  currency: "BRL",
                                })
                                : "R$ 0,00"}
                            </div>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap">
                            <span
                              className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${item.pre_venda
                                ? "bg-green-100 text-green-800"
                                : "bg-gray-100 text-gray-800"
                                }`}
                            >
                              {item.pre_venda ? "Sim" : "Não"}
                            </span>
                          </td>
                          <td className="px-6 py-4 whitespace-nowrap text-center">
                            <div className="flex items-center justify-center gap-2">
                              <button
                                onClick={() => handleEdit(item)}
                                className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                                title="Editar"
                              >
                                <Edit size={16} />
                              </button>
                              {(() => {
                                const hasEvents = events.some(event => 
                                  event.fotId === item.id || 
                                  (typeof event.fot === 'number' && event.fot === item.fot)
                                );
                                return (
                                  <button
                                    onClick={() => handleDelete(item.id, item.fot)}
                                    disabled={hasEvents}
                                    className={`p-1.5 rounded transition-colors ${
                                      hasEvents 
                                        ? "text-gray-400 cursor-not-allowed" 
                                        : "text-red-600 hover:bg-red-50"
                                    }`}
                                    title={hasEvents ? "Não é possível excluir: FOT possui eventos associados" : "Excluir"}
                                  >
                                    <Trash2 size={16} />
                                  </button>
                                );
                              })()}
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
              <div className="px-6 py-4 border-t border-gray-200 bg-gray-50 text-right">
                <span className="text-sm font-semibold text-gray-700">
                  Total de Registros: {filteredList.length}
                </span>
              </div>
            </>
          )}
        </div>
      </div>
    </div >
  );
};
