import React, { useState } from "react";
import { useData } from "../contexts/DataContext";
import { useAuth } from "../contexts/AuthContext";
import { UserRole, Course } from "../types";
import { CourseForm } from "../components/CourseForm";
import { Plus, Edit, Trash2 } from "lucide-react";
import { Button } from "../components/Button";

export const CourseManagement: React.FC = () => {
  const { user } = useAuth();
  const { institutions, courses, addCourse, updateCourse } = useData();

  const [showCourseForm, setShowCourseForm] = useState(false);
  const [editingCourse, setEditingCourse] = useState<Course | undefined>(
    undefined
  );

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

  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>
    );
  }

  const handleAddCourse = () => {
    setEditingCourse(undefined);
    setShowCourseForm(true);
  };

  const handleEditCourse = (course: Course) => {
    setEditingCourse(course);
    setShowCourseForm(true);
  };

  const handleSubmitCourse = (courseData: Partial<Course>) => {
    if (editingCourse) {
      updateCourse(editingCourse.id, courseData);
    } else {
      const newCourse: Course = {
        id: `course-${Date.now()}`,
        name: courseData.name || "",
        institutionId: courseData.institutionId || "",
        year: courseData.year || new Date().getFullYear(),
        semester: courseData.semester,
        graduationType: courseData.graduationType || "",
        createdAt: new Date().toISOString(),
        createdBy: user?.id || "",
        isActive: courseData.isActive !== false,
        ...courseData,
      };
      addCourse(newCourse);
    }
    setShowCourseForm(false);
    setEditingCourse(undefined);
  };

  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 items-center justify-between mb-2">
            <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={handleAddCourse}
              variant="secondary"
              className="flex items-center space-x-2"
            >
              <Plus size={16} />
              <span>Cadastrar Turma</span>
            </Button>
          </div>
        </div>

        {/* Course Form Modal */}
        {showCourseForm && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
            <CourseForm
              onCancel={() => {
                setShowCourseForm(false);
                setEditingCourse(undefined);
              }}
              onSubmit={handleSubmitCourse}
              initialData={editingCourse}
              userId={user?.id || ""}
              institutions={institutions}
            />
          </div>
        )}

        {/* Courses Table */}
        <div className="bg-white rounded-lg shadow border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <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">
                    Cursos
                  </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">
                    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">
                    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">
                {courses.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">
                        <p className="text-lg font-medium">
                          Nenhuma turma cadastrada
                        </p>
                        <p className="text-sm mt-1">
                          Clique em "Cadastrar Turma" para adicionar a primeira
                          turma
                        </p>
                      </div>
                    </td>
                  </tr>
                ) : (
                  courses.map((course) => (
                    <tr
                      key={course.id}
                      className="hover:bg-gray-50 transition-colors"
                    >
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm font-medium text-gray-900">
                          {(course as any).fotId || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).empresaNome || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).educationLevel || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm text-gray-600 max-w-xs truncate">
                          {(course as any).observacoes || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).instituicao || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).anoFormatura || course.year || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).cidade || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).estado || "-"}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-600">
                          {(course as any).gastosCaptacao || "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 ${
                            (course as any).preVenda === "sim"
                              ? "bg-green-100 text-green-800"
                              : "bg-gray-100 text-gray-800"
                          }`}
                        >
                          {(course as any).preVenda === "sim" ? "Sim" : "Não"}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-center">
                        <button
                          onClick={() => handleEditCourse(course)}
                          className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                          title="Editar turma"
                        >
                          <Edit size={16} />
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};
