import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useSettingsStore } from "@/store/useSettingsStore";
import { useSyncChannelId } from "@/hooks/useSyncChannelId";
import { DynamicTable } from "@/components/DynamicTable";
import {
	getFeedbacks,
	getFeedbackFields,
	type Feedback,
	type FeedbackField,
} from "@/services/feedback";
import { ErrorDisplay } from "@/components/ErrorDisplay";
import { Button } from "@/components/ui/button";

export function FeedbackListPage() {
	useSyncChannelId(); // URL의 channelId를 전역 상태와 동기화
	const { projectId, channelId } = useSettingsStore();
	const navigate = useNavigate();

	const [schema, setSchema] = useState<FeedbackField[] | null>(null);
	const [feedbacks, setFeedbacks] = useState<Feedback[]>([]);
	const [loading, setLoading] = useState<boolean>(true);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		if (!projectId || !channelId) return;

		const fetchSchemaAndFeedbacks = async () => {
			try {
				setLoading(true);
				setError(null);

				const schemaData = await getFeedbackFields(projectId, channelId);
				setSchema(schemaData);

				const feedbacksData = await getFeedbacks(projectId, channelId);
				setFeedbacks(feedbacksData);
			} catch (err) {
				setError(
					err instanceof Error ? err.message : "데이터 로딩에 실패했습니다.",
				);
			} finally {
				setLoading(false);
			}
		};

		fetchSchemaAndFeedbacks();
	}, [projectId, channelId]);

	const handleRowClick = (row: Feedback) => {
		navigate(
			`/projects/${projectId}/channels/${channelId}/feedbacks/${row.id}`,
		);
	};

	if (loading) {
		return <div className="text-center py-10">로딩 중...</div>;
	}

	return (
		<div className="space-y-4">
			<div className="flex justify-between items-center">
				<h1 className="text-2xl font-bold">피드백 목록</h1>
				<Button asChild>
					<Link to="new">새 피드백 작성</Link>
				</Button>
			</div>
			{error && <ErrorDisplay message={error} />}
			{schema && (
				<div className="mt-6">
					<DynamicTable
						columns={schema}
						data={feedbacks}
						onRowClick={handleRowClick}
					/>
				</div>
			)}
		</div>
	);
}
