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";
import { PageLayout } from "@/components/PageLayout";
import type { Row } from "@tanstack/react-table";

export function FeedbackListPage() {
	useSyncChannelId();
	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}`,
		);
	};

	const renderExpandedRow = (row: Row<Feedback>) => (
		<div className="p-4 bg-muted rounded-md">
			<h4 className="font-bold text-lg mb-2">{row.original.title}</h4>
			<p className="whitespace-pre-wrap">{row.original.contents}</p>
		</div>
	);

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

	return (
		<PageLayout
			title="피드백 목록"
			description="프로젝트의 피드백 목록입니다."
			actions={
				<Button asChild>
					<Link to="new">새 피드백 작성</Link>
				</Button>
			}
		>
			{error && <ErrorDisplay message={error} />}
			{schema && (
				<DynamicTable
					columns={schema}
					data={feedbacks}
					onRowClick={handleRowClick}
					renderExpandedRow={renderExpandedRow}
					projectId={projectId}
				/>
			)}
		</PageLayout>
	);
}
