import React, { useState, useEffect } from 'react';
import axios from 'axios';
import VideoPlayer from './VideoPlayer';
import { ChevronLeftIcon, ChevronRightIcon, PencilIcon, TrashIcon, PlayIcon } from '@heroicons/react/24/solid';

function MainApp() {
  const [channels, setChannels] = useState([]);
  const [customChannels, setCustomChannels] = useState([]);
  const [selectedChannel, setSelectedChannel] = useState(null);
  const [error, setError] = useState(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);
  const [isUploadMode, setIsUploadMode] = useState(false);
  const [jsonInput, setJsonInput] = useState('');
  const [editingChannel, setEditingChannel] = useState(null);
  const [urlInput, setUrlInput] = useState('');

  useEffect(() => {
    const fetchChannels = async () => {
      try {
        const response = await axios.get('http://127.0.0.1:5000/api/channels');
        setChannels(response.data);

        const storedChannels = JSON.parse(localStorage.getItem('userChannels')) || [];
        setCustomChannels(storedChannels);

        const urlParams = new URLSearchParams(window.location.search);
        const channelId = urlParams.get('channel');
        if (channelId) {
          const channel = [...response.data, ...storedChannels].find(c => c.id.toString() === channelId);
          if (channel) {
            setSelectedChannel(channel);
          }
        }
      } catch (error) {
        console.error('获取频道列表时出错:', error);
        setError('无法获取频道列表。请检查后端服务器是否正在运行。');
      }
    };

    fetchChannels();
  }, []);

  const handleChannelSelect = (channel) => {
    setSelectedChannel(channel);
    setIsUploadMode(false);
    const newUrl = `${window.location.pathname}?channel=${channel.id}`;
    window.history.pushState({ channelId: channel.id }, '', newUrl);
  };

  const handleJsonSubmit = () => {
    try {
      const json = JSON.parse(jsonInput);
      if (Array.isArray(json) && json.every(item => item.name && item.url)) {
        const newChannels = json.map((item, index) => ({
          id: `custom-${customChannels.length + index + 1}`,
          name: item.name,
          url: item.url
        }));
        const updatedChannels = [...customChannels, ...newChannels];
        setCustomChannels(updatedChannels);
        localStorage.setItem('userChannels', JSON.stringify(updatedChannels));
        setJsonInput('');
        setError(null);
      } else {
        setError('JSON 格式不正确。请确保文件包含 name 和 url 字段的对象数组。');
      }
    } catch (error) {
      setError('无法解析 JSON。请检查格式。');
    }
  };

  const toggleSidebar = () => {
    setIsSidebarOpen(!isSidebarOpen);
  };

  const toggleUploadMode = () => {
    setIsUploadMode(!isUploadMode);
    setSelectedChannel(null);
    setEditingChannel(null);
  };

  const handleEditChannel = (channel) => {
    setEditingChannel(channel);
  };

  const handleUpdateChannel = () => {
    const updatedChannels = customChannels.map(ch =>
      ch.id === editingChannel.id ? editingChannel : ch
    );
    setCustomChannels(updatedChannels);
    localStorage.setItem('userChannels', JSON.stringify(updatedChannels));
    setEditingChannel(null);
  };

  const handleDeleteChannel = (channelId) => {
    const updatedChannels = customChannels.filter(ch => ch.id !== channelId);
    setCustomChannels(updatedChannels);
    localStorage.setItem('userChannels', JSON.stringify(updatedChannels));
  };

  const handleUrlSubmit = (e) => {
    e.preventDefault();
    if (urlInput) {
      setSelectedChannel({ name: 'Custom URL', url: urlInput });
    }
  };

  return (
    <div className="flex h-screen bg-gray-100">
      {/* 侧边栏 */}
      <div className={`relative flex flex-col bg-white shadow-lg transition-all duration-300 ease-in-out ${isSidebarOpen ? 'w-64' : 'w-16'}`}>
        <div className="flex-grow overflow-y-auto p-4">
          <h2 className={`text-xl font-semibold mb-4 ${isSidebarOpen ? '' : 'hidden'}`}>频道列表</h2>
          <ul>
            {channels.map((channel) => (
              <li
                key={channel.id}
                className={`mb-2 p-2 cursor-pointer rounded ${
                  selectedChannel && selectedChannel.id === channel.id
                    ? 'bg-blue-500 text-white'
                    : 'hover:bg-gray-100'
                } ${isSidebarOpen ? '' : 'text-center'}`}
                onClick={() => handleChannelSelect(channel)}
              >
                {isSidebarOpen ? channel.name : channel.name.charAt(0)}
              </li>
            ))}
          </ul>
          {customChannels.length > 0 && (
            <>
              <h3 className={`text-lg font-semibold mt-6 mb-2 ${isSidebarOpen ? '' : 'hidden'}`}>自定义频道</h3>
              <ul>
                {customChannels.map((channel) => (
                  <li
                    key={channel.id}
                    className={`mb-2 p-2 cursor-pointer rounded ${
                      selectedChannel && selectedChannel.id === channel.id
                        ? 'bg-blue-500 text-white'
                        : 'hover:bg-gray-100'
                    } ${isSidebarOpen ? '' : 'text-center'}`}
                    onClick={() => handleChannelSelect(channel)}
                  >
                    {isSidebarOpen ? channel.name : channel.name.charAt(0)}
                  </li>
                ))}
              </ul>
            </>
          )}
        </div>

        {/* 输入字段和按钮 */}
        <div className={`p-4 border-t ${isSidebarOpen ? '' : 'hidden'}`}>
          <form onSubmit={handleUrlSubmit} className="flex flex-col">
            <input
              type="text"
              value={urlInput}
              onChange={(e) => setUrlInput(e.target.value)}
              placeholder="输入或粘贴 M3U8 URL"
              className="w-full p-2 border rounded mb-2"
            />
            <button
              type="submit"
              className="w-full p-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors flex items-center justify-center"
            >
              <PlayIcon className="h-5 w-5 mr-2" />
              播放
            </button>
          </form>
        </div>

        <div className={`mt-auto p-4 ${isSidebarOpen ? '' : 'hidden'}`}>
          <button
            onClick={toggleUploadMode}
            className="w-full p-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
          >
            {isUploadMode ? '返回播放器' : '管理自定义频道'}
          </button>
        </div>

        <button
          onClick={toggleSidebar}
          className="absolute top-0 right-0 mt-4 mr-4 p-1 rounded-full bg-gray-200 hover:bg-gray-300 focus:outline-none"
        >
          {isSidebarOpen ? (
            <ChevronLeftIcon className="h-6 w-6 text-gray-600" />
          ) : (
            <ChevronRightIcon className="h-6 w-6 text-gray-600" />
          )}
        </button>
      </div>

      {/* 主内容区 */}
      <div className="flex-1 p-8 overflow-y-auto">
        {error && <p className="text-red-500 mb-4">{error}</p>}
        {isUploadMode ? (
          <div className="w-full max-w-2xl mx-auto">
            <h2 className="text-2xl font-semibold mb-4">管理自定义频道</h2>
            <p className="mb-4">
              请在下方文本框中粘贴包含频道信息的 JSON 内容。JSON 应包含一个对象数组，每个对象有两个键：
              <code className="bg-gray-200 px-1 rounded">name</code> (频道名称) 和
              <code className="bg-gray-200 px-1 rounded">url</code> (流媒体 URL)。
            </p>
            <pre className="bg-gray-100 p-4 rounded mb-4">
              {JSON.stringify([
                { name: "示例频道 1", url: "http://example.com/stream1.m3u8" },
                { name: "示例频道 2", url: "http://example.com/stream2.m3u8" }
              ], null, 2)}
            </pre>
            <textarea
              className="w-full h-64 p-2 border rounded mb-4"
              value={jsonInput}
              onChange={(e) => setJsonInput(e.target.value)}
              placeholder="在此粘贴 JSON 内容..."
            />
            <button
              onClick={handleJsonSubmit}
              className="w-full p-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors mb-8"
            >
              添加频道
            </button>

            <h3 className="text-xl font-semibold mb-4">已上传的自定义频道</h3>
            <ul className="space-y-4">
              {customChannels.map((channel) => (
                <li key={channel.id} className="bg-white p-4 rounded shadow">
                  {editingChannel && editingChannel.id === channel.id ? (
                    <>
                      <input
                        type="text"
                        value={editingChannel.name}
                        onChange={(e) => setEditingChannel({...editingChannel, name: e.target.value})}
                        className="w-full p-2 border rounded mb-2"
                      />
                      <input
                        type="text"
                        value={editingChannel.url}
                        onChange={(e) => setEditingChannel({...editingChannel, url: e.target.value})}
                        className="w-full p-2 border rounded mb-2"
                      />
                      <button
                        onClick={handleUpdateChannel}
                        className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 transition-colors"
                      >
                        保存
                      </button>
                    </>
                  ) : (
                    <>
                      <h4 className="font-semibold">{channel.name}</h4>
                      <p className="text-sm text-gray-600 mb-2">{channel.url}</p>
                      <div className="flex space-x-2">
                        <button
                          onClick={() => handleEditChannel(channel)}
                          className="p-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 transition-colors"
                        >
                          <PencilIcon className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteChannel(channel.id)}
                          className="p-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
                        >
                          <TrashIcon className="h-4 w-4" />
                        </button>
                      </div>
                    </>
                  )}
                </li>
              ))}
            </ul>
          </div>
        ) : selectedChannel ? (
          <div className="w-full max-w-4xl mx-auto">
            <h2 className="text-2xl font-semibold mb-4">{selectedChannel.name}</h2>
            <VideoPlayer streamUrl={selectedChannel.url} />
          </div>
        ) : (
          <p className="text-gray-600">请从左侧选择一个频道或输入 M3U8 URL</p>
        )}
      </div>
    </div>
  );
}

export default MainApp;
