'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Collection } from '../../types/api';
import { collectionApi, audioCoveApi, getImageUrl } from '../../lib/api';
import Button from '../ui/Button';
import StoryReorderList from './StoryReorderList';
import AddToCollectionModal from './AddToCollectionModal';
import LoadingSpinner from '../ui/LoadingSpinner';
import Link from 'next/link';

interface CollectionDetailViewProps {
  collection: Collection;
  onUpdate: () => void;
  onDelete: () => void;
}

export default function CollectionDetailView({
  collection,
  onUpdate,
  onDelete
}: CollectionDetailViewProps) {
  const router = useRouter();
  const [showAddStories, setShowAddStories] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editName, setEditName] = useState(collection.name);
  const [editDescription, setEditDescription] = useState(collection.description || '');
  const [editRating, setEditRating] = useState(collection.rating || '');
  const [saving, setSaving] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [isSendingToAudioCove, setIsSendingToAudioCove] = useState(false);
  const [audioCoveSuccess, setAudioCoveSuccess] = useState(false);

  const formatReadingTime = (minutes: number): string => {
    if (minutes < 60) {
      return `${minutes} minutes`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours} hours`;
  };

  const renderRatingStars = (rating?: number) => {
    if (!rating) return null;
    
    return (
      <div className="flex items-center">
        {[1, 2, 3, 4, 5].map((star) => (
          <span
            key={star}
            className={`text-lg ${
              star <= rating ? 'text-yellow-400' : 'text-gray-300'
            }`}
          >
            ★
          </span>
        ))}
      </div>
    );
  };

  const handleSaveEdits = async () => {
    try {
      setSaving(true);
      await collectionApi.updateCollection(collection.id, {
        name: editName.trim(),
        description: editDescription.trim() || undefined,
        rating: editRating ? parseInt(editRating.toString()) : undefined,
      });
      setIsEditing(false);
      onUpdate();
    } catch (error) {
      console.error('Failed to update collection:', error);
    } finally {
      setSaving(false);
    }
  };

  const handleCancelEdit = () => {
    setEditName(collection.name);
    setEditDescription(collection.description || '');
    setEditRating(collection.rating || '');
    setIsEditing(false);
  };

  const handleArchive = async () => {
    const action = collection.isArchived ? 'unarchive' : 'archive';
    if (confirm(`Are you sure you want to ${action} this collection?`)) {
      try {
        setActionLoading('archive');
        await collectionApi.archiveCollection(collection.id, !collection.isArchived);
        onUpdate();
      } catch (error) {
        console.error(`Failed to ${action} collection:`, error);
      } finally {
        setActionLoading(null);
      }
    }
  };

  const handleDelete = async () => {
    if (confirm('Are you sure you want to delete this collection? This cannot be undone. Stories will not be deleted.')) {
      try {
        setActionLoading('delete');
        await collectionApi.deleteCollection(collection.id);
        onDelete();
      } catch (error) {
        console.error('Failed to delete collection:', error);
      } finally {
        setActionLoading(null);
      }
    }
  };

  const startReading = () => {
    if (collection.collectionStories && collection.collectionStories.length > 0) {
      const firstStory = collection.collectionStories[0].story;
      router.push(`/collections/${collection.id}/read/${firstStory.id}`);
    }
  };

  const handleSendToAudioCove = async () => {
    if (isSendingToAudioCove) return;
    setIsSendingToAudioCove(true);
    try {
      await audioCoveApi.sendCollectionToAudioCove(collection.id);
      setAudioCoveSuccess(true);
      setTimeout(() => setAudioCoveSuccess(false), 3000);
    } catch (error: any) {
      const message = error?.response?.data || 'Failed to send to AudioCove. Please try again.';
      alert(message);
    } finally {
      setIsSendingToAudioCove(false);
    }
  };

  return (
    <div className="space-y-8">
      {/* Header Section */}
      <div className="theme-card p-6">
        <div className="flex flex-col lg:flex-row gap-6">
          {/* Cover Image */}
          <div className="flex-shrink-0">
            <div className="w-48 h-64 rounded-lg overflow-hidden bg-gray-100 mx-auto lg:mx-0">
              {collection.coverImagePath ? (
                <img
                  src={getImageUrl(collection.coverImagePath)}
                  alt={`${collection.name} cover`}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
                  <div className="text-center p-4">
                    <div className="text-3xl font-bold theme-text mb-2">
                      {collection.storyCount}
                    </div>
                    <div className="text-sm theme-text opacity-60">
                      {collection.storyCount === 1 ? 'story' : 'stories'}
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Collection Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1 min-w-0">
                {isEditing ? (
                  <div className="space-y-3">
                    <input
                      type="text"
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      className="text-3xl font-bold theme-header bg-transparent border-b-2 border-gray-300 focus:border-blue-500 focus:outline-none w-full"
                    />
                    <textarea
                      value={editDescription}
                      onChange={(e) => setEditDescription(e.target.value)}
                      placeholder="Add a description..."
                      rows={3}
                      className="w-full theme-text bg-transparent border border-gray-300 rounded-lg p-2 focus:border-blue-500 focus:outline-none resize-none"
                    />
                    <div className="flex items-center gap-4">
                      <label className="text-sm font-medium theme-text">Rating:</label>
                      <select
                        value={editRating}
                        onChange={(e) => setEditRating(e.target.value)}
                        className="px-3 py-1 border border-gray-300 rounded theme-text focus:border-blue-500 focus:outline-none"
                      >
                        <option value="">No rating</option>
                        {[1, 2, 3, 4, 5].map(num => (
                          <option key={num} value={num}>{num} star{num > 1 ? 's' : ''}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                ) : (
                  <div>
                    <h1 className="text-3xl font-bold theme-header mb-2 break-words">
                      {collection.name}
                      {collection.isArchived && (
                        <span className="ml-3 inline-block bg-yellow-500 text-white px-3 py-1 rounded text-sm font-normal">
                          Archived
                        </span>
                      )}
                    </h1>
                    {collection.description && (
                      <p className="theme-text text-lg mb-4 whitespace-pre-wrap">
                        {collection.description}
                      </p>
                    )}
                    {collection.rating && (
                      <div className="mb-4">
                        {renderRatingStars(collection.rating)}
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Edit Controls */}
              <div className="flex gap-2 ml-4">
                {isEditing ? (
                  <>
                    <Button
                      size="sm"
                      onClick={handleSaveEdits}
                      disabled={saving || !editName.trim()}
                    >
                      {saving ? <LoadingSpinner size="sm" /> : 'Save'}
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={handleCancelEdit}
                      disabled={saving}
                    >
                      Cancel
                    </Button>
                  </>
                ) : (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setIsEditing(true)}
                  >
                    Edit
                  </Button>
                )}
              </div>
            </div>

            {/* Statistics */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="text-center">
                <div className="text-2xl font-bold theme-text">
                  {collection.storyCount}
                </div>
                <div className="text-sm theme-text opacity-60">
                  {collection.storyCount === 1 ? 'Story' : 'Stories'}
                </div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold theme-text">
                  {collection.estimatedReadingTime ? formatReadingTime(collection.estimatedReadingTime) : '—'}
                </div>
                <div className="text-sm theme-text opacity-60">Reading Time</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold theme-text">
                  {collection.totalWordCount ? collection.totalWordCount.toLocaleString() : '0'}
                </div>
                <div className="text-sm theme-text opacity-60">Total Words</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold theme-text">
                  {collection.averageStoryRating && collection.averageStoryRating > 0 ? collection.averageStoryRating.toFixed(1) : '—'}
                </div>
                <div className="text-sm theme-text opacity-60">Avg Rating</div>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex flex-wrap gap-3">
              <Button
                onClick={startReading}
                disabled={collection.storyCount === 0}
                className="flex-shrink-0"
              >
                Read Collection
              </Button>
              <Button
                variant="ghost"
                onClick={() => router.push(`/collections/${collection.id}/edit`)}
                className="flex-shrink-0"
              >
                Edit Collection
              </Button>
              <Button
                variant="ghost"
                onClick={() => setShowAddStories(true)}
                className="flex-shrink-0"
              >
                Add Stories
              </Button>
              <Button
                variant="ghost"
                onClick={handleArchive}
                disabled={actionLoading === 'archive'}
                className="flex-shrink-0"
              >
                {actionLoading === 'archive' ? <LoadingSpinner size="sm" /> : (collection.isArchived ? 'Unarchive' : 'Archive')}
              </Button>
              <Button
                variant="ghost"
                onClick={handleDelete}
                disabled={actionLoading === 'delete'}
                className="flex-shrink-0 text-red-600 hover:text-red-800"
              >
                {actionLoading === 'delete' ? <LoadingSpinner size="sm" /> : 'Delete'}
              </Button>
              <Button
                variant="ghost"
                onClick={handleSendToAudioCove}
                disabled={isSendingToAudioCove || audioCoveSuccess || collection.storyCount === 0}
                className="flex-shrink-0"
              >
                {isSendingToAudioCove ? '🎧 Sending...' : audioCoveSuccess ? '✅ Sent!' : '🎧 Send to Audiocove'}
              </Button>
            </div>

            {/* Tags */}
            {collection.tags && collection.tags.length > 0 && (
              <div className="mt-6">
                <h3 className="text-sm font-medium theme-text mb-2">Tags:</h3>
                <div className="flex flex-wrap gap-2">
                  {collection.tags.map((tag) => (
                    <span
                      key={tag.id}
                      className="inline-block px-3 py-1 text-sm rounded-full theme-accent-bg text-white"
                    >
                      {tag.name}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Stories Section */}
      <div className="theme-card p-6">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-semibold theme-header">
            Stories ({collection.storyCount})
          </h2>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowAddStories(true)}
          >
            Add Stories
          </Button>
        </div>

        <StoryReorderList
          collection={collection}
          onUpdate={onUpdate}
        />
      </div>

      {/* Add Stories Modal */}
      <AddToCollectionModal
        isOpen={showAddStories}
        onClose={() => setShowAddStories(false)}
        collection={collection}
        onUpdate={onUpdate}
      />
    </div>
  );
}