"use client";

import { useCallback, useEffect, useState } from "react";
import { api } from "@/lib/api";
import type { Review } from "@/lib/api";
import { useAuth } from "@/lib/auth-context";

interface ReviewSectionProps {
  restaurantId: string;
}

function StarDisplay({ rating }: { rating: number }) {
  const stars = [];
  for (let i = 1; i <= 5; i++) {
    if (rating >= i) {
      stars.push(
        <span key={i} className="text-yellow-500">
          ★
        </span>
      );
    } else if (rating >= i - 0.5) {
      stars.push(
        <span key={i} className="text-yellow-500">
          ★
        </span>
      );
    } else {
      stars.push(
        <span key={i} className="text-gray-300">
          ★
        </span>
      );
    }
  }
  return <span className="text-sm">{stars}</span>;
}

function StarSelector({
  value,
  onChange,
}: {
  value: number;
  onChange: (v: number) => void;
}) {
  return (
    <div className="flex items-center gap-1">
      <span className="text-xs text-gray-500 mr-1">별점:</span>
      {[0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5].map((v) => (
        <button
          key={v}
          type="button"
          onClick={() => onChange(v)}
          className={`w-6 h-6 text-xs rounded border ${
            value === v
              ? "bg-yellow-500 text-white border-yellow-600"
              : "bg-white text-gray-600 border-gray-300 hover:border-yellow-400"
          }`}
        >
          {v}
        </button>
      ))}
    </div>
  );
}

function ReviewForm({
  initialRating = 3,
  initialText = "",
  initialDate = "",
  onSubmit,
  onCancel,
  submitLabel,
}: {
  initialRating?: number;
  initialText?: string;
  initialDate?: string;
  onSubmit: (data: {
    rating: number;
    review_text?: string;
    visited_at?: string;
  }) => Promise<void>;
  onCancel: () => void;
  submitLabel: string;
}) {
  const [rating, setRating] = useState(initialRating);
  const [text, setText] = useState(initialText);
  const [visitedAt, setVisitedAt] = useState(initialDate);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await onSubmit({
        rating,
        review_text: text || undefined,
        visited_at: visitedAt || undefined,
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-3 border rounded-lg p-3">
      <StarSelector value={rating} onChange={setRating} />
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="리뷰를 작성해주세요 (선택)"
        className="w-full border rounded p-2 text-sm resize-none"
        rows={3}
      />
      <div className="flex items-center gap-2">
        <label className="text-xs text-gray-500">방문일:</label>
        <input
          type="date"
          value={visitedAt}
          onChange={(e) => setVisitedAt(e.target.value)}
          className="border rounded px-2 py-1 text-xs"
        />
      </div>
      <div className="flex gap-2">
        <button
          type="submit"
          disabled={submitting}
          className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
        >
          {submitting ? "저장 중..." : submitLabel}
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="px-3 py-1 bg-gray-200 text-gray-700 text-sm rounded hover:bg-gray-300"
        >
          취소
        </button>
      </div>
    </form>
  );
}

export default function ReviewSection({ restaurantId }: ReviewSectionProps) {
  const { user } = useAuth();
  const [reviews, setReviews] = useState<Review[]>([]);
  const [avgRating, setAvgRating] = useState<number | null>(null);
  const [reviewCount, setReviewCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);

  const loadReviews = useCallback(() => {
    setLoading(true);
    api
      .getReviews(restaurantId)
      .then((data) => {
        setReviews(data.reviews);
        setAvgRating(data.avg_rating);
        setReviewCount(data.review_count);
      })
      .catch(() => setReviews([]))
      .finally(() => setLoading(false));
  }, [restaurantId]);

  useEffect(() => {
    loadReviews();
  }, [loadReviews]);

  const myReview = user
    ? reviews.find((r) => r.user_id === user.id)
    : null;

  const handleCreate = async (data: {
    rating: number;
    review_text?: string;
    visited_at?: string;
  }) => {
    await api.createReview(restaurantId, data);
    setShowForm(false);
    loadReviews();
  };

  const handleUpdate = async (
    reviewId: string,
    data: { rating: number; review_text?: string; visited_at?: string }
  ) => {
    await api.updateReview(reviewId, data);
    setEditingId(null);
    loadReviews();
  };

  const handleDelete = async (reviewId: string) => {
    if (!confirm("리뷰를 삭제하시겠습니까?")) return;
    await api.deleteReview(reviewId);
    loadReviews();
  };

  return (
    <div>
      <h3 className="font-semibold text-sm mb-2">리뷰</h3>

      {loading ? (
        <div className="space-y-3 animate-pulse">
          <div className="flex items-center gap-2">
            <div className="h-4 w-24 bg-gray-200 rounded" />
            <div className="h-4 w-8 bg-gray-200 rounded" />
          </div>
          {[1, 2].map((i) => (
            <div key={i} className="space-y-1">
              <div className="h-3 w-20 bg-gray-200 rounded" />
              <div className="h-3 w-full bg-gray-200 rounded" />
            </div>
          ))}
        </div>
      ) : (
        <>
          {reviewCount > 0 && avgRating !== null && (
            <div className="flex items-center gap-2 mb-3 text-sm">
              <StarDisplay rating={Math.round(avgRating * 2) / 2} />
              <span className="font-medium">{avgRating.toFixed(1)}</span>
              <span className="text-gray-500">({reviewCount}개)</span>
            </div>
          )}

          {user && !myReview && !showForm && (
            <button
              onClick={() => setShowForm(true)}
              className="mb-3 px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
            >
              리뷰 작성
            </button>
          )}

          {showForm && (
            <div className="mb-3">
              <ReviewForm
                onSubmit={handleCreate}
                onCancel={() => setShowForm(false)}
                submitLabel="작성"
              />
            </div>
          )}

          {reviews.length === 0 ? (
            <p className="text-sm text-gray-500">아직 리뷰가 없습니다</p>
          ) : (
            <div className="space-y-3">
              {reviews.map((review) => (
                <div key={review.id} className="border rounded-lg p-3">
                  {editingId === review.id ? (
                    <ReviewForm
                      initialRating={review.rating}
                      initialText={review.review_text || ""}
                      initialDate={review.visited_at || ""}
                      onSubmit={(data) => handleUpdate(review.id, data)}
                      onCancel={() => setEditingId(null)}
                      submitLabel="수정"
                    />
                  ) : (
                    <>
                      <div className="flex items-center gap-2 mb-1">
                        {review.user_avatar_url && (
                          <img
                            src={review.user_avatar_url}
                            alt=""
                            className="w-5 h-5 rounded-full"
                          />
                        )}
                        <span className="text-sm font-medium">
                          {review.user_nickname || "익명"}
                        </span>
                        <StarDisplay rating={review.rating} />
                        <span className="text-xs text-gray-400">
                          {new Date(review.created_at).toLocaleDateString(
                            "ko-KR"
                          )}
                        </span>
                      </div>
                      {review.review_text && (
                        <p className="text-sm text-gray-700 mt-1">
                          {review.review_text}
                        </p>
                      )}
                      {review.visited_at && (
                        <p className="text-xs text-gray-400 mt-1">
                          방문일: {review.visited_at}
                        </p>
                      )}
                      {user && review.user_id === user.id && (
                        <div className="flex gap-2 mt-2">
                          <button
                            onClick={() => setEditingId(review.id)}
                            className="text-xs text-blue-600 hover:underline"
                          >
                            수정
                          </button>
                          <button
                            onClick={() => handleDelete(review.id)}
                            className="text-xs text-red-600 hover:underline"
                          >
                            삭제
                          </button>
                        </div>
                      )}
                    </>
                  )}
                </div>
              ))}
            </div>
          )}
        </>
      )}
    </div>
  );
}
