import React, { useState, useEffect } from 'react';
import { CheckCircle2, Circle, Plus, X } from 'lucide-react';

interface ChecklistItem {
  id: string;
  title: string;
  completed: boolean;
  completed_at?: string;
}

interface DailyChecklist {
  id: number;
  checklist_date: string;
  checklist_type: string;
  items: ChecklistItem[];
  completion_percentage: number;
  notes?: string;
  created_at: string;
  updated_at: string;
}

interface DailyChecklistPanelProps {
  checklistType?: 'morning' | 'active_trading' | 'evening' | 'all';
}

const DailyChecklistPanel: React.FC<DailyChecklistPanelProps> = ({
  checklistType = 'morning',
}) => {
  const [checklist, setChecklist] = useState<DailyChecklist | null>(null);
  const [loading, setLoading] = useState(false);
  const [newItemTitle, setNewItemTitle] = useState('');
  const [showAddForm, setShowAddForm] = useState(false);
  const [notes, setNotes] = useState('');

  useEffect(() => {
    loadChecklist();
    // Refresh every minute
    const interval = setInterval(loadChecklist, 60000);
    return () => clearInterval(interval);
  }, [checklistType]);

  const loadChecklist = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/daily-helper/checklists/today');
      if (response.ok) {
        const data: DailyChecklist | null = await response.json();
        if (data) {
          setChecklist(data);
          setNotes(data.notes || '');
        } else {
          // Create default checklist
          await createDefaultChecklist();
        }
      }
    } catch (err) {
      console.error('Failed to load checklist:', err);
    } finally {
      setLoading(false);
    }
  };

  const createDefaultChecklist = async () => {
    const defaultItems = {
      morning: [
        { id: '1', title: 'Check Economic Calendar', completed: false },
        { id: '2', title: 'Scan Market News', completed: false },
        { id: '3', title: 'Analyze Market Sentiment', completed: false },
        { id: '4', title: 'Identify Key Levels', completed: false },
        { id: '5', title: 'Create Trading Plan', completed: false },
      ],
      active_trading: [
        { id: '1', title: 'Monitor Price Action', completed: false },
        { id: '2', title: 'Execute Per Plan', completed: false },
        { id: '3', title: 'Manage Open Positions', completed: false },
        { id: '4', title: 'Track Breaking News', completed: false },
        { id: '5', title: 'Log Trades', completed: false },
      ],
      evening: [
        { id: '1', title: 'Review All Trades', completed: false },
        { id: '2', title: 'Complete Trading Journal', completed: false },
        { id: '3', title: 'Analyze Performance', completed: false },
        { id: '4', title: 'Update Key Levels', completed: false },
        { id: '5', title: 'Plan for Tomorrow', completed: false },
      ],
    };

    const type = (checklistType === 'all' ? 'morning' : checklistType) as keyof typeof defaultItems;

    try {
      const response = await fetch('/api/daily-helper/checklists', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          checklist_type: type,
          items: defaultItems[type],
          notes: '',
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setChecklist(data);
      }
    } catch (err) {
      console.error('Failed to create default checklist:', err);
    }
  };

  const handleToggleItem = async (itemId: string, completed: boolean) => {
    if (!checklist) return;

    try {
      const response = await fetch(
        `/api/daily-helper/checklists/${checklist.id}/items/${itemId}`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ completed: !completed }),
        }
      );

      if (response.ok) {
        const updated = await response.json();
        setChecklist(updated);
      }
    } catch (err) {
      console.error('Failed to update checklist item:', err);
    }
  };

  const handleAddItem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!checklist || !newItemTitle.trim()) return;

    const newItem: ChecklistItem = {
      id: Date.now().toString(),
      title: newItemTitle,
      completed: false,
    };

    const updatedItems = [...checklist.items, newItem];

    try {
      const response = await fetch(`/api/daily-helper/checklists/${checklist.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items: updatedItems,
        }),
      });

      if (response.ok) {
        const updated = await response.json();
        setChecklist(updated);
        setNewItemTitle('');
        setShowAddForm(false);
      }
    } catch (err) {
      console.error('Failed to add item:', err);
    }
  };

  const handleRemoveItem = async (itemId: string) => {
    if (!checklist) return;

    const updatedItems = checklist.items.filter((item) => item.id !== itemId);

    try {
      const response = await fetch(`/api/daily-helper/checklists/${checklist.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items: updatedItems,
        }),
      });

      if (response.ok) {
        const updated = await response.json();
        setChecklist(updated);
      }
    } catch (err) {
      console.error('Failed to remove item:', err);
    }
  };

  const handleSaveNotes = async () => {
    if (!checklist) return;

    try {
      const response = await fetch(`/api/daily-helper/checklists/${checklist.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          notes: notes,
        }),
      });

      if (response.ok) {
        const updated = await response.json();
        setChecklist(updated);
      }
    } catch (err) {
      console.error('Failed to save notes:', err);
    }
  };

  if (loading) {
    return (
      <div className="bg-gray-900 rounded-lg border border-gray-700 p-6">
        <div className="text-center text-gray-400">Loading checklist...</div>
      </div>
    );
  }

  if (!checklist) {
    return (
      <div className="bg-gray-900 rounded-lg border border-gray-700 p-6">
        <div className="text-center text-gray-400">No checklist found</div>
      </div>
    );
  }

  return (
    <div className="bg-gray-900 rounded-lg border border-gray-700 p-6">
      {/* Header */}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-white capitalize mb-2">
          {checklist.checklist_type} Checklist
        </h2>
        <div className="flex items-center gap-4">
          <div className="flex-1">
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm text-gray-400">Completion</span>
              <span className="text-sm font-semibold text-white">
                {Math.round(checklist.completion_percentage)}%
              </span>
            </div>
            <div className="w-full h-2 bg-gray-800 rounded-full overflow-hidden">
              <div
                className="h-full bg-gradient-to-r from-blue-600 to-blue-400 transition-all duration-300"
                style={{ width: `${checklist.completion_percentage}%` }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Checklist Items */}
      <div className="space-y-2 mb-6">
        {checklist.items.map((item) => (
          <div
            key={item.id}
            className="flex items-center gap-3 p-3 bg-gray-800 rounded-lg hover:bg-gray-750 transition-colors group"
          >
            <button
              onClick={() => handleToggleItem(item.id, item.completed)}
              className="flex-shrink-0 text-gray-400 hover:text-blue-400 transition-colors"
            >
              {item.completed ? (
                <CheckCircle2 size={24} className="text-green-500" />
              ) : (
                <Circle size={24} />
              )}
            </button>

            <span
              className={`flex-1 ${
                item.completed
                  ? 'line-through text-gray-500'
                  : 'text-gray-200'
              }`}
            >
              {item.title}
            </span>

            <button
              onClick={() => handleRemoveItem(item.id)}
              className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-red-400 transition-all"
            >
              <X size={18} />
            </button>
          </div>
        ))}
      </div>

      {/* Add Item Form */}
      {showAddForm ? (
        <form onSubmit={handleAddItem} className="mb-6 p-4 bg-gray-800 rounded-lg">
          <div className="flex gap-2 mb-3">
            <input
              type="text"
              value={newItemTitle}
              onChange={(e) => setNewItemTitle(e.target.value)}
              placeholder="New checklist item..."
              className="flex-1 bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white placeholder-gray-500 focus:outline-none focus:border-blue-500"
              autoFocus
            />
          </div>
          <div className="flex gap-2">
            <button
              type="submit"
              className="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded transition-colors"
            >
              Add
            </button>
            <button
              type="button"
              onClick={() => {
                setShowAddForm(false);
                setNewItemTitle('');
              }}
              className="flex-1 bg-gray-700 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded transition-colors"
            >
              Cancel
            </button>
          </div>
        </form>
      ) : (
        <button
          onClick={() => setShowAddForm(true)}
          className="w-full bg-gray-800 hover:bg-gray-700 text-gray-300 font-medium py-2 px-4 rounded flex items-center justify-center gap-2 transition-colors mb-6"
        >
          <Plus size={20} />
          Add Item
        </button>
      )}

      {/* Notes Section */}
      <div className="border-t border-gray-700 pt-6">
        <h3 className="text-sm font-semibold text-gray-300 mb-2">Notes</h3>
        <textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          onBlur={handleSaveNotes}
          placeholder="Add notes for today's trading..."
          className="w-full h-24 bg-gray-800 border border-gray-600 rounded px-3 py-2 text-white placeholder-gray-500 focus:outline-none focus:border-blue-500 resize-none"
        />
      </div>

      {/* Stats */}
      <div className="mt-6 grid grid-cols-3 gap-4 p-4 bg-gray-800 rounded-lg">
        <div>
          <p className="text-xs text-gray-400 mb-1">Total Items</p>
          <p className="text-2xl font-bold text-white">{checklist.items.length}</p>
        </div>
        <div>
          <p className="text-xs text-gray-400 mb-1">Completed</p>
          <p className="text-2xl font-bold text-green-400">
            {checklist.items.filter((i) => i.completed).length}
          </p>
        </div>
        <div>
          <p className="text-xs text-gray-400 mb-1">Remaining</p>
          <p className="text-2xl font-bold text-orange-400">
            {checklist.items.filter((i) => !i.completed).length}
          </p>
        </div>
      </div>
    </div>
  );
};

export default DailyChecklistPanel;
