import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import QuestList from '../components/QuestList';
import QuestForm from '../components/QuestForm';
import QuestFilterBar from '../components/QuestFilterBar';
import { QuestCompletionModal } from '../components/minigames/QuestCompletionModal';
import AppHeader from '../components/AppHeader';
import { apiService } from '../services/api';
import { Quest, Location, Member, User } from '../types';
import { Button } from '../components/ui/Button';
import { Alert } from '../components/ui/Alert';

interface QuestsPageProps {
  user: User;
  onLogout: () => void;
}

const QuestsPage: React.FC<QuestsPageProps> = ({ user, onLogout }) => {
  const location = useLocation();
  const [quests, setQuests] = useState<Quest[]>([]);
  const [locations, setLocations] = useState<Location[]>([]);
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingQuest, setEditingQuest] = useState<Quest | undefined>();
  const [prefilledQuest, setPrefilledQuest] = useState<Partial<Quest> | undefined>();
  const [filterStatus, setFilterStatus] = useState<string | null>(null);
  const [filterLocation, setFilterLocation] = useState<number | null>(null);
  const [filterType, setFilterType] = useState<string | null>(null);
  const [gold, setGold] = useState<number>(user.gold || 0);
  const [completionModalOpen, setCompletionModalOpen] = useState(false);
  const [selectedQuestForCompletion, setSelectedQuestForCompletion] = useState<Quest | null>(null);
  const [completionToast, setCompletionToast] = useState<{ title: string; message: string; variant: 'success' | 'error' } | null>(null);

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

  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const status = params.get('status');
    if (status) {
      setFilterStatus(status);
    }

    const shouldPropose = params.get('propose') === '1';
    if (shouldPropose) {
      const seedType = params.get('seedType');
      const seedPriority = params.get('seedPriority');
      const seedLocationId = params.get('seedLocationId');

      const allowedTypes: Quest['quest_type'][] = ['The Journey', 'The Battle', 'The Fellowship', 'The Ring', 'Dark Magic'];
      const allowedPriorities: Quest['priority'][] = ['Critical', 'Important', 'Standard'];

      const questType = allowedTypes.includes(seedType as Quest['quest_type'])
        ? (seedType as Quest['quest_type'])
        : 'The Journey';

      const priority = allowedPriorities.includes(seedPriority as Quest['priority'])
        ? (seedPriority as Quest['priority'])
        : 'Important';

      const locationId = seedLocationId ? Number(seedLocationId) : undefined;

      setEditingQuest(undefined);
      setPrefilledQuest({
        title: params.get('seedTitle') || 'Scout the frontier',
        description: params.get('seedDescription') || 'Investigate the region and report meaningful leads.',
        status: 'not_yet_begun',
        quest_type: questType,
        priority,
        location_id: Number.isNaN(locationId) ? undefined : locationId,
      });
      setShowForm(true);
    }
  }, [location.search]);

  // Handle quest selection from map navigation
  useEffect(() => {
    if (location.state?.selectedQuestId && quests.length > 0) {
      const selectedQuest = quests.find(q => q.id === location.state.selectedQuestId);
      if (selectedQuest) {
        setEditingQuest(selectedQuest);
        setShowForm(true);
      }
    }
  }, [location.state?.selectedQuestId, quests]);

  useEffect(() => {
    if (quests.length === 0) {
      return;
    }

    const params = new URLSearchParams(location.search);
    const focusQuestIdRaw = params.get('focusQuestId');
    if (!focusQuestIdRaw) {
      return;
    }

    const focusQuestId = Number(focusQuestIdRaw);
    if (!focusQuestId || Number.isNaN(focusQuestId)) {
      return;
    }

    const selectedQuest = quests.find(q => q.id === focusQuestId);
    if (selectedQuest) {
      setEditingQuest(selectedQuest);
      setShowForm(true);
    }
  }, [location.search, quests]);

  const loadData = async () => {
    try {
      const [questsData, locationsData, membersData] = await Promise.all([
        apiService.getQuests(),
        apiService.getLocations(),
        apiService.getMembers(),
      ]);
      setQuests(questsData);
      setLocations(locationsData);
      setMembers(membersData);
      const currentGold = await apiService.getGoldBalance();
      setGold(currentGold);
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateQuest = async (questData: Partial<Quest>) => {
    await apiService.createQuest(questData);
    await loadData();
    setShowForm(false);
    setPrefilledQuest(undefined);
  };

  const handleUpdateQuest = async (questData: Partial<Quest>) => {
    if (editingQuest) {
      await apiService.updateQuest(editingQuest.id, questData);
      await loadData();
      setEditingQuest(undefined);
      setPrefilledQuest(undefined);
    }
  };

  const handleDeleteQuest = async (id: number) => {
    if (window.confirm('Are you sure you want to abandon this quest?')) {
      await apiService.deleteQuest(id);
      await loadData();
    }
  };

  const handleCompleteQuest = async (id: number) => {
    const quest = quests.find(q => q.id === id);
    if (quest) {
      setSelectedQuestForCompletion(quest);
      setCompletionModalOpen(true);
    }
  };

  const handleClaimReward = async (questId: number) => {
    try {
      const result = await apiService.completeQuest(questId);
      if ((result as any).current_gold !== undefined) {
        setGold((result as any).current_gold);
      }
      setCompletionToast({
        title: 'Quest reward claimed',
        message: result.message + ((result as any).character_quote ? ` — "${(result as any).character_quote}"` : ''),
        variant: 'success',
      });
      await loadData();
    } catch (error) {
      console.error('Failed to complete quest:', error);
      setCompletionToast({
        title: 'Quest completion failed',
        message: 'The shadow may have fallen upon it. Please try again.',
        variant: 'error',
      });
    }
  };

  useEffect(() => {
    if (!completionToast) {
      return;
    }

    const timeout = window.setTimeout(() => {
      setCompletionToast(null);
    }, 5000);

    return () => window.clearTimeout(timeout);
  }, [completionToast]);

  const handleEditQuest = (quest: Quest) => {
    setEditingQuest(quest);
    setPrefilledQuest(undefined);
    setShowForm(true);
  };

  const handleFormCancel = () => {
    setShowForm(false);
    setEditingQuest(undefined);
    setPrefilledQuest(undefined);
  };

  const handleFormSubmit = async (questData: Partial<Quest>) => {
    if (editingQuest) {
      await handleUpdateQuest(questData);
    } else {
      await handleCreateQuest(questData);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl mb-4">📜</div>
          <p className="text-text-primary font-readable">Unfurling the Scrolls of Middle-earth...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <AppHeader
        page="quests"
        gold={gold}
        completedQuests={quests.filter(q => q.status === 'it_is_done').length}
        averageSavings={null}
        onLogout={onLogout}
      />

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 py-8">
        {completionToast && (
          <div className="fixed right-4 top-24 z-[60] w-full max-w-md">
            <Alert
              variant={completionToast.variant}
              title={completionToast.title}
              onClose={() => setCompletionToast(null)}
              className="shadow-2xl backdrop-blur"
            >
              {completionToast.message}
            </Alert>
          </div>
        )}

        {/* Page Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <p className="font-readable text-text-muted text-lg">
              All {quests.length} quest objectives across the realm
            </p>
          </div>
          <Button
            onClick={() => {
              setEditingQuest(undefined);
              setPrefilledQuest(undefined);
              setShowForm(true);
            }}
            variant="epic"
          >
            🗂️ Propose a Quest
          </Button>
        </div>

        {/* Quest Filter Bar */}
        <QuestFilterBar
          quests={quests}
          locations={locations}
          onStatusChange={setFilterStatus}
          onTypeChange={setFilterType}
          onLocationChange={setFilterLocation}
          selectedStatus={filterStatus}
          selectedType={filterType}
          selectedLocation={filterLocation}
        />

        {/* Quest List */}
        <div data-tour="quests-overview">
          <QuestList
            quests={quests.filter(
              q => (filterStatus ? q.status === filterStatus : true) &&
                   (filterType ? q.quest_type === filterType : true) &&
                   (filterLocation ? q.location_id === filterLocation : true)
            )}
            onEdit={handleEditQuest}
            onDelete={handleDeleteQuest}
            onComplete={handleCompleteQuest}
          />
        </div>
      </div>

      {/* Quest Form Modal */}
      {showForm && (
        <QuestForm
          quest={editingQuest || prefilledQuest}
          locations={locations}
          members={members}
          onSubmit={handleFormSubmit}
          onCancel={handleFormCancel}
        />
      )}

      {/* Quest Completion Modal */}
      {selectedQuestForCompletion && (
        <QuestCompletionModal
          isOpen={completionModalOpen}
          onClose={() => {
            setCompletionModalOpen(false);
            setSelectedQuestForCompletion(null);
          }}
          onComplete={handleClaimReward}
          questId={selectedQuestForCompletion.id}
          questTitle={selectedQuestForCompletion.title}
        />
      )}
    </div>
  );
};

export default QuestsPage;

