'use client';

import React, { useEffect, useState, useMemo } from 'react';
import { IProject, IClientPortalConfig, DEFAULT_CLIENT_PORTAL_CONFIG } from '@alga-psa/types';
import { ClientPortalProjectMetrics } from '@alga-psa/client-portal-composition';
import { formatDistanceToNow, format } from 'date-fns';
import { getDateFnsLocale } from '@alga-psa/ui';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import ViewSwitcher from '@alga-psa/ui/components/ViewSwitcher';
import {
  getClientProjectPhases,
  getClientProjectTasks,
  getClientProjectStatuses
} from '@alga-psa/client-portal/actions';
import ClientKanbanBoard from './ClientKanbanBoard';
import ClientTaskListView from './ClientTaskListView';
import { LayoutGrid, List } from 'lucide-react';

interface ProjectDetailViewProps {
  project: IProject;
}

type ViewMode = 'kanban' | 'list';

interface Phase {
  phase_id: string;
  phase_name: string;
  description: string | null;
  start_date: Date | null;
  end_date: Date | null;
  completion_percentage?: number;
}

interface Status {
  project_status_mapping_id: string;
  name: string;
  display_order: number;
  is_closed: boolean;
  color: string | null;
}

interface Task {
  task_id: string;
  phase_id: string;
  project_status_mapping_id: string;
  task_name?: string;
  description?: string;
  due_date?: Date | null;
  status_name?: string;
  custom_name?: string;
  assigned_to_name?: string;
  estimated_hours?: number | null;
  actual_hours?: number | null;
  is_closed?: boolean;
  checklist_total?: number;
  checklist_completed?: number;
}

interface TaskDependency {
  dependency_id: string;
  predecessor_task_id: string;
  successor_task_id: string;
  dependency_type: 'blocks' | 'blocked_by' | 'related_to';
  predecessor_task?: { task_name: string };
  successor_task?: { task_name: string };
}

const VIEW_MODE_STORAGE_KEY = 'client-portal-project-view-mode';

export default function ProjectDetailView({ project }: ProjectDetailViewProps) {
  const { t, i18n } = useTranslation('features/projects');
  const { t: tCommon } = useTranslation('common');
  const dateLocale = getDateFnsLocale(i18n.language);

  // Initialize viewMode from localStorage
  const [viewMode, setViewMode] = useState<ViewMode>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem(VIEW_MODE_STORAGE_KEY);
      if (saved === 'kanban' || saved === 'list') {
        return saved;
      }
    }
    return 'kanban';
  });

  // Data states
  const [phases, setPhases] = useState<Phase[]>([]);
  const [statuses, setStatuses] = useState<Status[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [taskDependencies, setTaskDependencies] = useState<{ [taskId: string]: { predecessors: TaskDependency[]; successors: TaskDependency[] } }>({});
  const [selectedPhaseId, setSelectedPhaseId] = useState<string | null>(null);
  const [dataLoading, setDataLoading] = useState(true);

  // Persist viewMode to localStorage when it changes
  const handleViewModeChange = (newMode: ViewMode) => {
    setViewMode(newMode);
    if (typeof window !== 'undefined') {
      localStorage.setItem(VIEW_MODE_STORAGE_KEY, newMode);
    }
  };

  // Get client portal config with default fallback
  const config = project.client_portal_config ?? DEFAULT_CLIENT_PORTAL_CONFIG;
  const showPhases = config.show_phases ?? false;
  const showTasks = config.show_tasks ?? false;
  const showBudgetHours = config.show_budget_hours ?? false;

  // Determine effective view mode - kanban only makes sense when tasks are shown
  // When only phases are enabled (no tasks), force list view
  const effectiveViewMode = showTasks ? viewMode : 'list';

  // Load phases
  useEffect(() => {
    const fetchData = async () => {
      if (!showPhases && !showTasks) {
        setDataLoading(false);
        return;
      }

      setDataLoading(true);
      try {
        const phasesResult = showPhases ? await getClientProjectPhases(project.project_id) : null;

        if (phasesResult?.phases) {
          setPhases(phasesResult.phases);
          // Auto-select first phase for kanban view
          if (phasesResult.phases.length > 0 && !selectedPhaseId) {
            setSelectedPhaseId(phasesResult.phases[0].phase_id);
          }
        }
      } catch (error) {
        console.error('Error fetching phases:', error);
      } finally {
        setDataLoading(false);
      }
    };

    fetchData();
  }, [project.project_id, selectedPhaseId, showPhases, showTasks]);

  useEffect(() => {
    const fetchStatuses = async () => {
      if (!showTasks) {
        setStatuses([]);
        return;
      }

      try {
        const statusesResult = await getClientProjectStatuses(project.project_id, selectedPhaseId);
        if (statusesResult?.statuses) {
          setStatuses(statusesResult.statuses);
        } else {
          setStatuses([]);
        }
      } catch (error) {
        console.error('Error fetching phase statuses:', error);
      }
    };

    fetchStatuses();
  }, [project.project_id, selectedPhaseId, showTasks]);

  // Load tasks - single function handles both views
  useEffect(() => {
    const fetchTasks = async () => {
      // Skip if tasks are not shown - phases are fetched by the first useEffect
      if (!showTasks) {
        setDataLoading(false);
        return;
      }

      setDataLoading(true);
      try {
        // Fetch all tasks - filtering by phase is done in the component for kanban view
        const result = await getClientProjectTasks(project.project_id);

        if (result?.tasks) {
          setTasks(result.tasks);
        }
        if (result?.taskDependencies) {
          setTaskDependencies(result.taskDependencies);
        } else {
          setTaskDependencies({});
        }
        // Use phases from result if we don't have them yet (e.g., phases not separately enabled)
        if (result?.phases && phases.length === 0) {
          setPhases(result.phases.map((p: { phase_id: string; phase_name: string; description?: string | null; start_date?: Date | null; end_date?: Date | null }) => ({
            phase_id: p.phase_id,
            phase_name: p.phase_name,
            description: p.description ?? null,
            start_date: p.start_date ?? null,
            end_date: p.end_date ?? null
          })));
        }
      } catch (error) {
        console.error('Error fetching tasks:', error);
      } finally {
        setDataLoading(false);
      }
    };

    fetchTasks();
  }, [project.project_id, showTasks, effectiveViewMode]);

  // View switcher options
  const viewOptions = useMemo(() => [
    { value: 'kanban' as ViewMode, label: t('kanbanView', 'Kanban'), icon: LayoutGrid },
    { value: 'list' as ViewMode, label: t('listView', 'List'), icon: List }
  ], [t]);

  return (
    <div className="space-y-6">
      {/* Project Header Card */}
      <div className="p-6 bg-white rounded-lg shadow">
        <h2 className="text-2xl font-bold mb-2">{project.project_name}</h2>
        <p className="text-gray-600 mb-6">
          {project.description || t('messages.noDescription', 'No description provided')}
        </p>

        <ClientPortalProjectMetrics projectId={project.project_id} showBudgetHours={showBudgetHours} />

        <div>
          <h3 className="text-lg font-semibold mb-2">{t('details')}</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p className="text-sm text-gray-600">{t('startDate')}</p>
              <p className="font-medium">
                {project.start_date
                  ? new Date(project.start_date).toLocaleDateString()
                  : tCommon('common.notSpecified', 'Not specified')}
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-600">{t('endDate')}</p>
              <p className="font-medium">
                {project.end_date
                  ? new Date(project.end_date).toLocaleDateString()
                  : tCommon('common.notSpecified', 'Not specified')}
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-600">{t('lastUpdated', 'Last Updated')}</p>
              <p className="font-medium">
                {project.updated_at
                  ? formatDistanceToNow(new Date(project.updated_at), { addSuffix: true, locale: dateLocale })
                  : tCommon('common.unknown', 'Unknown')}
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-600">{t('fields.status')}</p>
              <p className="font-medium">{project.status_name ? t(`status.${project.status_name.toLowerCase().replace(/\s+/g, '')}`, project.status_name) : t('status.active', 'Active')}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Tasks Section - with View Switcher */}
      {(showPhases || showTasks) && (
        <div className="bg-white rounded-lg shadow">
          {/* Header with View Switcher */}
          <div className="p-4 border-b border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div className="flex items-center gap-4">
                <h3 className="text-lg font-semibold">
                  {showPhases && showTasks
                    ? t('phasesAndTasks', 'Phases & Tasks')
                    : showPhases
                      ? t('phases.title', 'Project Phases')
                      : t('tasks.title', 'Tasks')}
                </h3>
              </div>

              {/* View Switcher */}
              {showTasks && (
                <ViewSwitcher
                  currentView={viewMode}
                  onChange={handleViewModeChange}
                  options={viewOptions}
                />
              )}
            </div>
          </div>

          {/* Content */}
          <div className="p-4">
            {effectiveViewMode === 'kanban' ? (
              <ClientKanbanBoard
                phases={phases}
                statuses={statuses}
                tasks={tasks}
                config={config}
                selectedPhaseId={selectedPhaseId}
                onPhaseSelect={setSelectedPhaseId}
                loading={dataLoading}
                taskDependencies={taskDependencies}
              />
            ) : (
              <ClientTaskListView
                phases={phases}
                tasks={tasks}
                config={config}
                loading={dataLoading}
                taskDependencies={taskDependencies}
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
