'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import StarRating from './StarRating';

interface ReviewFormProps {
  projectId: string;
  freelancerId: string;
  onSubmit?: (reviewData: any) => void;
  onCancel?: () => void;
  initialData?: {
    rating: number;
    comment: string;
  };
  mode?: 'create' | 'edit';
  reviewId?: string;
}

interface ProjectDetails {
  id: string;
  title: string;
  description: string;
  freelancer: {
    id: string;
    name: string;
    profileImage: string;
  };
}

export default function ReviewForm({
  projectId,
  freelancerId,
  onSubmit,
  onCancel,
  initialData,
  mode = 'create',
  reviewId
}: ReviewFormProps) {
  const [rating, setRating] = useState(initialData?.rating || 0);
  const [comment, setComment] = useState(initialData?.comment || '');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [projectDetails, setProjectDetails] = useState<ProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const router = useRouter();

  useEffect(() => {
    fetchProjectDetails();
  }, [projectId, freelancerId]);

  const fetchProjectDetails = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}`);
      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data) {
          setProjectDetails({
            id: data.data.id,
            title: data.data.title,
            description: data.data.description,
            freelancer: {
              id: freelancerId,
              name: data.data.freelancerName || 'Freelancer',
              profileImage: data.data.freelancerImage || '/assets/image/user.png'
            }
          });
        }
      }
    } catch (error) {
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (rating === 0) {
      setError('Please select a rating');
      return;
    }

    if (comment.trim().length < 10) {
      setError('Review must be at least 10 characters long');
      return;
    }

    setIsSubmitting(true);

    try {
      const reviewData = {
        projectId,
        freelancerId,
        rating,
        review: comment.trim()
      };

      const url = mode === 'edit' && reviewId 
        ? `/api/reviews/${reviewId}` 
        : '/api/reviews';
      
      const method = mode === 'edit' ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(reviewData),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        if (onSubmit) {
          onSubmit(data.review);
        } else {
          router.back();
        }
      } else {
        setError(data.error || `Failed to ${mode} review`);
      }
    } catch (error) {
      setError(`Failed to ${mode} review. Please try again.`);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCancel = () => {
    if (onCancel) {
      onCancel();
    } else {
      router.back();
    }
  };

  if (isLoading) {
    return (
      <div className="review-form-loading">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="review-form-container">
      <div className="review-form-card">
        <div className="form-header">
          <h4>{mode === 'edit' ? 'Edit Review' : 'Write a Review'}</h4>
          {projectDetails && (
            <div className="project-info">
              <div className="freelancer-info">
                <img 
                  src={projectDetails.freelancer.profileImage} 
                  alt={projectDetails.freelancer.name}
                  className="freelancer-avatar"
                />
                <div className="freelancer-details">
                  <span className="freelancer-name">{projectDetails.freelancer.name}</span>
                  <span className="project-title">{projectDetails.title}</span>
                </div>
              </div>
            </div>
          )}
        </div>

        <form onSubmit={handleSubmit} className="review-form">
          <div className="form-group">
            <label className="form-label">
              Rating <span className="required">*</span>
            </label>
            <div className="rating-input">
              <StarRating
                rating={rating}
                onRatingChange={setRating}
                size="lg"
                showText={true}
              />
            </div>
          </div>

          <div className="form-group">
            <label htmlFor="comment" className="form-label">
              Review <span className="required">*</span>
            </label>
            <textarea
              id="comment"
              className="form-control"
              rows={5}
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder="Share details about your experience working with this freelancer..."
              minLength={10}
              maxLength={1000}
              required
            />
            <div className="char-count">
              {comment.length}/1000 characters
            </div>
          </div>

          {error && (
            <div className="alert alert-danger">
              {error}
            </div>
          )}

          <div className="form-actions">
            <button
              type="button"
              onClick={handleCancel}
              className="btn btn-outline-secondary"
              disabled={isSubmitting}
            >
              Cancel
            </button>
            <button
              type="submit"
              className="btn btn-primary"
              disabled={isSubmitting || rating === 0 || comment.trim().length < 10}
            >
              {isSubmitting ? (
                <>
                  <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                  {mode === 'edit' ? 'Updating...' : 'Submitting...'}
                </>
              ) : (
                mode === 'edit' ? 'Update Review' : 'Submit Review'
              )}
            </button>
          </div>
        </form>
      </div>

      <style jsx>{`
        .review-form-container {
          max-width: 600px;
          margin: 0 auto;
          padding: 20px;
        }

        .review-form-loading {
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 200px;
        }

        .review-form-card {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 12px;
          padding: 30px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .form-header {
          margin-bottom: 30px;
          text-align: center;
        }

        .form-header h4 {
          color: var(--typo-secondary);
          font-weight: 600;
          margin-bottom: 20px;
        }

        .project-info {
          padding: 15px;
          background: var(--color-light-gray);
          border-radius: 8px;
          margin-bottom: 10px;
        }

        .freelancer-info {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .freelancer-avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid var(--color-white);
        }

        .freelancer-details {
          display: flex;
          flex-direction: column;
        }

        .freelancer-name {
          font-weight: 600;
          color: var(--typo-secondary);
          font-size: var(--font-small);
        }

        .project-title {
          font-size: var(--font-xs);
          color: var(--text-color);
          font-style: italic;
        }

        .review-form {
          display: flex;
          flex-direction: column;
          gap: 25px;
        }

        .form-group {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .form-label {
          font-weight: 500;
          color: var(--typo-secondary);
          font-size: var(--font-small);
        }

        .required {
          color: var(--color-danger);
        }

        .rating-input {
          display: flex;
          justify-content: flex-start;
        }

        .form-control {
          border: 2px solid var(--border-color);
          border-radius: 8px;
          padding: 12px;
          font-size: var(--font-small);
          transition: border-color 0.3s ease;
          resize: vertical;
          min-height: 120px;
        }

        .form-control:focus {
          border-color: var(--color-primary);
          outline: none;
          box-shadow: 0 0 0 0.2rem rgba(251, 97, 7, 0.25);
        }

        .char-count {
          text-align: right;
          font-size: var(--font-xs);
          color: var(--text-color);
        }

        .form-actions {
          display: flex;
          gap: 15px;
          justify-content: flex-end;
          margin-top: 10px;
        }

        .btn {
          padding: 12px 24px;
          font-size: var(--font-small);
          font-weight: 500;
          border-radius: 8px;
          transition: all 0.3s ease;
          min-width: 120px;
        }

        .btn-primary {
          background-color: var(--color-primary);
          border-color: var(--color-primary);
          color: var(--color-white);
        }

        .btn-primary:hover:not(:disabled) {
          background-color: #e55a06;
          border-color: #e55a06;
        }

        .btn-primary:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        .btn-outline-secondary {
          background-color: transparent;
          border-color: var(--border-color);
          color: var(--text-color);
        }

        .btn-outline-secondary:hover:not(:disabled) {
          background-color: var(--color-light-gray);
          border-color: var(--text-color);
        }

        .alert {
          padding: 12px;
          border-radius: 6px;
          font-size: var(--font-small);
        }

        .alert-danger {
          background-color: #f8d7da;
          border-color: #f5c6cb;
          color: #721c24;
        }

        @media (max-width: 768px) {
          .review-form-container {
            padding: 15px;
          }

          .review-form-card {
            padding: 20px;
          }

          .form-actions {
            flex-direction: column-reverse;
          }

          .btn {
            width: 100%;
          }

          .freelancer-info {
            gap: 8px;
          }

          .freelancer-avatar {
            width: 40px;
            height: 40px;
          }
        }
      `}</style>
    </div>
  );
}