'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Star, ArrowLeft, ChevronLeft, ChevronRight, MessageSquare } from 'lucide-react';

interface Feedback {
    id: string;
    rating: number;
    comment: string;
    date: string;
}

interface FeedbackStats {
    total: number;
    avgRating: number;
    distribution: { [key: number]: number };
}

interface Pagination {
    page: number;
    totalPages: number;
    hasMore: boolean;
}

export default function FeedbackListPage() {
    const params = useParams();
    const router = useRouter();
    const qrId = params.id as string;

    const [feedbacks, setFeedbacks] = useState<Feedback[]>([]);
    const [stats, setStats] = useState<FeedbackStats | null>(null);
    const [pagination, setPagination] = useState<Pagination>({ page: 1, totalPages: 1, hasMore: false });
    const [loading, setLoading] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);

    useEffect(() => {
        fetchFeedback(currentPage);
    }, [qrId, currentPage]);

    const fetchFeedback = async (page: number) => {
        setLoading(true);
        try {
            const res = await fetch(`/api/qrs/${qrId}/feedback?page=${page}&limit=20`);
            if (res.ok) {
                const data = await res.json();
                setFeedbacks(data.feedbacks);
                setStats(data.stats);
                setPagination(data.pagination);
            }
        } catch (error) {
            console.error('Error fetching feedback:', error);
        } finally {
            setLoading(false);
        }
    };

    const renderStars = (rating: number) => (
        <div className="flex gap-0.5">
            {[1, 2, 3, 4, 5].map((star) => (
                <Star
                    key={star}
                    className={`w-4 h-4 ${star <= rating ? 'text-amber-400 fill-amber-400' : 'text-gray-200'}`}
                />
            ))}
        </div>
    );

    if (loading && !stats) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
            </div>
        );
    }

    return (
        <div className="max-w-4xl mx-auto">
            {/* Header */}
            <div className="mb-8">
                <Link href={`/qr/${qrId}`} className="inline-flex items-center text-gray-500 hover:text-gray-700 mb-4">
                    <ArrowLeft className="w-4 h-4 mr-2" />
                    Back to QR Code
                </Link>
                <h1 className="text-3xl font-bold text-gray-900">Customer Feedback</h1>
                <p className="text-gray-600 mt-1">{stats?.total || 0} total responses</p>
            </div>

            {/* Stats Overview */}
            {stats && (
                <Card className="mb-8">
                    <CardContent className="p-6">
                        <div className="flex flex-col md:flex-row md:items-center gap-8">
                            {/* Average Rating */}
                            <div className="text-center md:text-left">
                                <div className="text-5xl font-bold text-gray-900 mb-1">{stats.avgRating}</div>
                                <div className="flex justify-center md:justify-start mb-1">
                                    {renderStars(Math.round(stats.avgRating))}
                                </div>
                                <p className="text-sm text-gray-500">{stats.total} reviews</p>
                            </div>

                            {/* Distribution */}
                            <div className="flex-1 space-y-2">
                                {[5, 4, 3, 2, 1].map((rating) => {
                                    const count = stats.distribution[rating] || 0;
                                    const percentage = stats.total > 0 ? (count / stats.total) * 100 : 0;
                                    return (
                                        <div key={rating} className="flex items-center gap-3">
                                            <span className="text-sm text-gray-600 w-12">{rating} stars</span>
                                            <div className="flex-1 h-2 bg-gray-100 rounded-full overflow-hidden">
                                                <div
                                                    className="h-full bg-amber-400 rounded-full transition-all"
                                                    style={{ width: `${percentage}%` }}
                                                />
                                            </div>
                                            <span className="text-sm text-gray-500 w-12 text-right">{count}</span>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Feedback List */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <MessageSquare className="w-5 h-5" />
                        All Reviews
                    </CardTitle>
                </CardHeader>
                <CardContent>
                    {feedbacks.length === 0 ? (
                        <div className="text-center py-12 text-gray-500">
                            <Star className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                            <p>No feedback received yet</p>
                        </div>
                    ) : (
                        <div className="divide-y divide-gray-100">
                            {feedbacks.map((feedback) => (
                                <div key={feedback.id} className="py-4">
                                    <div className="flex items-center justify-between mb-2">
                                        {renderStars(feedback.rating)}
                                        <span className="text-sm text-gray-400">
                                            {new Date(feedback.date).toLocaleDateString('en-US', {
                                                month: 'short',
                                                day: 'numeric',
                                                year: 'numeric',
                                            })}
                                        </span>
                                    </div>
                                    {feedback.comment && (
                                        <p className="text-gray-700">{feedback.comment}</p>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}

                    {/* Pagination */}
                    {pagination.totalPages > 1 && (
                        <div className="flex items-center justify-between mt-6 pt-6 border-t">
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                                disabled={currentPage === 1}
                            >
                                <ChevronLeft className="w-4 h-4 mr-1" />
                                Previous
                            </Button>
                            <span className="text-sm text-gray-500">
                                Page {currentPage} of {pagination.totalPages}
                            </span>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setCurrentPage((p) => p + 1)}
                                disabled={!pagination.hasMore}
                            >
                                Next
                                <ChevronRight className="w-4 h-4 ml-1" />
                            </Button>
                        </div>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
