// src/pages/CharacterHomeworks.tsx

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';

interface Homework {
  id: number;
  is_done: boolean;
  last_completed_at: string;
  homework_type: {
    title: string;
    reset_type: string;
  };
}

function CharacterHomeworksPage() {
  const { characterId } = useParams();
  const [homeworks, setHomeworks] = useState<Homework[]>([]);
  const [message, setMessage] = useState('');

  const fetchHomeworks = async () => {
    try {
      const token = localStorage.getItem('token');
      const res = await axios.get(`/homeworks/character/${characterId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      setHomeworks(res.data);
    } catch (err) {
      setMessage('숙제 목록 불러오기 실패');
    }
  };

  const completeHomework = async (id: number) => {
    try {
      const token = localStorage.getItem('token');
      await axios.post(`/homeworks/complete/${id}`, {}, {
        headers: { Authorization: `Bearer ${token}` },
      });
      fetchHomeworks();
    } catch {
      setMessage('숙제 완료 실패');
    }
  };

  useEffect(() => {
    fetchHomeworks();
  }, [characterId]);

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <h2 className="text-2xl font-semibold text-center text-blue-600 mb-6">숙제 목록</h2>
      {message && <p className="text-center text-red-500">{message}</p>}
      <div className="space-y-4">
        {homeworks.map((hw) => (
          <div
            key={hw.id}
            className={`p-4 rounded-xl shadow-md flex items-center justify-between ${hw.is_done ? 'bg-green-100' : 'bg-white'}`}
          >
            <div>
              <p className="font-bold">{hw.homework_type.title}</p>
              <p className="text-sm text-gray-600">주기: {hw.homework_type.reset_type}</p>
            </div>
            <button
              disabled={hw.is_done}
              onClick={() => completeHomework(hw.id)}
              className="bg-blue-600 text-white px-4 py-2 rounded-md disabled:bg-gray-300"
            >
              {hw.is_done ? '완료됨' : '완료하기'}
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

export default CharacterHomeworksPage;

