"use client";

import React, { useState, useEffect } from 'react';
import { BookOpen, Folder, FileText, Loader2 } from 'lucide-react';

interface Mission {
  id: string;
  name: string;
  logoUrl?: string | null;
  createdAt: string;
  updatedAt: string;
  isClosed?: boolean;
  missionUsers?: Array<{ role: string }>;
}

interface MissionsViewProps {
  onMissionSelect: (mission: Mission) => void;
  selectedMissionId?: string;
}

export const MissionsView: React.FC<MissionsViewProps> = ({ onMissionSelect, selectedMissionId }) => {
  const [missions, setMissions] = useState<Mission[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchMissions = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const response = await fetch('/api/missions/user');
        
        if (!response.ok) {
          throw new Error('Failed to fetch missions');
        }
        
        const data = await response.json();
        setMissions(data.missions || []);
      } catch (err) {
        console.error('Error fetching missions:', err);
        setError(err instanceof Error ? err.message : 'Failed to load missions');
      } finally {
        setIsLoading(false);
      }
    };

    fetchMissions();
  }, []);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="h-6 w-6 animate-spin text-carnet-text-muted" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <p className="text-red-500 mb-2">Erreur</p>
          <p className="text-carnet-text-muted text-sm">{error}</p>
        </div>
      </div>
    );
  }

  if (missions.length === 0) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <BookOpen className="h-12 w-12 text-carnet-text-muted mx-auto mb-4" />
          <p className="text-carnet-text-muted">Aucune mission</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-carnet-bg">
      <div className="p-4 border-b border-carnet-border">
        <div className="flex items-center space-x-2">
          <BookOpen className="h-5 w-5 text-carnet-text-primary" />
          <h2 className="text-lg font-semibold text-carnet-text-primary">Missions</h2>
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto">
        <ul className="divide-y divide-carnet-border">
          {missions.map((mission) => (
            <li
              key={mission.id}
              onClick={() => onMissionSelect(mission)}
              className={`p-4 hover:bg-carnet-hover cursor-pointer ${
                selectedMissionId === mission.id ? 'bg-carnet-hover' : ''
              }`}
            >
              <div className="flex items-center space-x-3">
                {mission.logoUrl ? (
                  <img
                    src={mission.logoUrl}
                    alt={mission.name}
                    className="w-10 h-10 rounded object-cover"
                  />
                ) : (
                  <div className="w-10 h-10 rounded bg-carnet-hover flex items-center justify-center">
                    <BookOpen className="h-5 w-5 text-carnet-text-muted" />
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-carnet-text-primary truncate">
                    {mission.name}
                  </p>
                  {mission.isClosed && (
                    <p className="text-xs text-carnet-text-muted">Fermée</p>
                  )}
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};
