"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/contexts/AuthContext";
import { solutionsApi, SolutionAdmin, getUploadUrl } from "@/lib/api";
import {
  Plus,
  Pencil,
  Trash2,
  Eye,
  EyeOff,
  Loader2,
  Image as ImageIcon,
} from "lucide-react";

export default function SolutionsListPage() {
  const { token } = useAuth();
  const [solutions, setSolutions] = useState<SolutionAdmin[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const fetchSolutions = async () => {
    if (!token) return;
    try {
      const data = await solutionsApi.adminGetAll(token);
      setSolutions(data);
    } catch (err) {
      console.error("Failed to fetch solutions:", err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchSolutions();
  }, [token]);

  const handleDelete = async (id: number) => {
    if (!token || !confirm("정말 삭제하시겠습니까?")) return;

    try {
      await solutionsApi.adminDelete(id, token);
      setSolutions(solutions.filter((s) => s.id !== id));
    } catch (err) {
      alert("삭제에 실패했습니다.");
    }
  };

  const toggleActive = async (solution: SolutionAdmin) => {
    if (!token) return;

    try {
      await solutionsApi.adminUpdate(
        solution.id,
        { is_active: !solution.is_active },
        token
      );
      setSolutions(
        solutions.map((s) =>
          s.id === solution.id ? { ...s, is_active: !s.is_active } : s
        )
      );
    } catch (err) {
      alert("상태 변경에 실패했습니다.");
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-[#3B82F6]" />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <h1 className="text-2xl font-bold text-gray-900">솔루션 관리</h1>
        <Link
          href="/admin/solutions/new"
          className="flex items-center px-4 py-2 bg-[#3B82F6] text-white font-medium rounded-lg hover:bg-[#2563EB] transition-colors"
        >
          <Plus className="w-5 h-5 mr-2" />
          새 솔루션
        </Link>
      </div>

      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 border-b">
            <tr>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                이미지
              </th>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                솔루션명
              </th>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                아이콘
              </th>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                색상
              </th>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                순서
              </th>
              <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">
                상태
              </th>
              <th className="px-6 py-4 text-right text-sm font-medium text-gray-500">
                관리
              </th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {solutions.length === 0 ? (
              <tr>
                <td colSpan={7} className="px-6 py-12 text-center text-gray-500">
                  등록된 솔루션이 없습니다.
                </td>
              </tr>
            ) : (
              solutions.map((solution) => (
                <tr key={solution.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    {solution.main_image ? (
                      <img
                        src={getUploadUrl(solution.main_image)}
                        alt={solution.title_ko}
                        className="w-16 h-12 object-cover rounded"
                      />
                    ) : (
                      <div className="w-16 h-12 bg-gray-100 rounded flex items-center justify-center">
                        <ImageIcon className="w-5 h-5 text-gray-400" />
                      </div>
                    )}
                  </td>
                  <td className="px-6 py-4">
                    <div className="font-medium text-gray-900">
                      {solution.title_ko}
                    </div>
                    {solution.title_en && (
                      <div className="text-sm text-gray-500">
                        {solution.title_en}
                      </div>
                    )}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">
                    {solution.icon || "-"}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">
                    {solution.color || "-"}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">
                    {solution.display_order}
                  </td>
                  <td className="px-6 py-4">
                    <button
                      onClick={() => toggleActive(solution)}
                      className={`flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                        solution.is_active
                          ? "bg-green-100 text-green-700"
                          : "bg-gray-100 text-gray-500"
                      }`}
                    >
                      {solution.is_active ? (
                        <>
                          <Eye className="w-3 h-3 mr-1" />
                          표시
                        </>
                      ) : (
                        <>
                          <EyeOff className="w-3 h-3 mr-1" />
                          숨김
                        </>
                      )}
                    </button>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center justify-end space-x-2">
                      <Link
                        href={`/admin/solutions/${solution.id}`}
                        className="p-2 text-gray-400 hover:text-[#3B82F6] transition-colors"
                      >
                        <Pencil className="w-5 h-5" />
                      </Link>
                      <button
                        onClick={() => handleDelete(solution.id)}
                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
