<template>
  <div class="p-4 sm:p-6">
    <!-- Loading State -->
    <div v-if="isLoadingProject" class="flex items-center justify-center py-12">
      <div class="flex items-center gap-2">
        <div
          class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"
        ></div>
        <span class="text-muted-foreground">Loading project...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="projectError" class="text-center py-12">
      <AlertCircle class="h-12 w-12 mx-auto text-destructive mb-4" />
      <h3 class="text-lg font-semibold mb-2">Project not found</h3>
      <p class="text-muted-foreground mb-4">{{ projectError }}</p>
      <Button @click="$router.push('/projects')" variant="outline">
        <ArrowLeft class="h-4 w-4 mr-2" />
        Back to Projects
      </Button>
    </div>

    <!-- Main Content -->
    <div v-else class="space-y-6">
      <!-- Page Header -->
      <div>
        <h1 class="text-2xl font-bold">Project Settings</h1>
        <p class="text-muted-foreground mt-1">
          Manage project configuration, team members, and production settings
        </p>
      </div>

      <!-- Tabbed Interface -->
      <Tabs :default-value="activeTab" @update:model-value="(val) => activeTab = String(val)" class="w-full">
        <TabsList class="grid w-full grid-cols-6">
          <TabsTrigger value="general">
            <Settings class="h-4 w-4 mr-2" />
            General
          </TabsTrigger>
          <TabsTrigger value="episodes">
            <Film class="h-4 w-4 mr-2" />
            Episodes
          </TabsTrigger>
          <TabsTrigger value="team">
            <Users class="h-4 w-4 mr-2" />
            Team
          </TabsTrigger>
          <TabsTrigger value="technical">
            <Cog class="h-4 w-4 mr-2" />
            Technical
          </TabsTrigger>
          <TabsTrigger value="tasks">
            <ListChecks class="h-4 w-4 mr-2" />
            Tasks
          </TabsTrigger>
          <TabsTrigger value="storage">
            <FolderOpen class="h-4 w-4 mr-2" />
            Storage
          </TabsTrigger>
        </TabsList>

        <!-- General Settings Tab -->
        <TabsContent value="general" class="mt-6">
          <div class="space-y-6">
            <!-- Project Thumbnail Section -->
            <div class="bg-card rounded-lg border p-6">
              <ProjectThumbnailUpload
                v-if="project"
                :project-id="project.id"
                :current-thumbnail-url="project.thumbnail_url"
                :project-name="project.name"
                @thumbnail-updated="handleThumbnailUpdated"
                @thumbnail-removed="handleThumbnailRemoved"
              />
            </div>

            <Separator />

            <!-- Project Details Section -->
            <div class="bg-card rounded-lg border p-6">
              <ProjectEditForm
                v-if="project"
                :project="project"
                @project-updated="handleProjectUpdate"
              />
            </div>
          </div>
        </TabsContent>

        <!-- Episodes Management Tab -->
        <TabsContent value="episodes" class="mt-6">
          <div class="bg-card rounded-lg border p-6">
            <EpisodeManagementSection
              :project-id="projectId"
              :can-manage="canManageProject"
            />
          </div>
        </TabsContent>

        <!-- Team Management Tab -->
        <TabsContent value="team" class="mt-6">
          <div class="bg-card rounded-lg border p-6">
            <ProjectMemberManagement :project-id="projectId" />
          </div>
        </TabsContent>

        <!-- Technical Specifications Tab -->
        <TabsContent value="technical" class="mt-6">
          <div class="bg-card rounded-lg border p-6">
            <TechnicalSpecsManager
              :project-id="projectId"
              :user-department="userDepartment"
            />
          </div>
        </TabsContent>

        <!-- Default Task Templates Tab -->
        <TabsContent value="tasks" class="mt-6">
          <div class="space-y-6">
            <!-- Custom Task Status Manager -->
            <div class="bg-card rounded-lg border p-6">
              <CustomTaskStatusManager
                :project-id="projectId"
                @updated="handleTaskStatusesUpdated"
              />
            </div>

            <Separator />

            <!-- Custom Task Type Manager -->
            <div class="bg-card rounded-lg border p-6">
              <CustomTaskTypeManager
                ref="customTaskTypeManagerRef"
                :project-id="projectId"
                @updated="handleTaskTypesUpdated"
              />
            </div>

            <Separator />

            <!-- Default Task Templates Editor -->
            <div class="bg-card rounded-lg border p-6">
              <DefaultTaskTemplatesEditor
                ref="taskTemplatesEditorRef"
                :project-id="projectId"
                :initial-asset-templates="projectSettings.assetTemplates"
                :initial-shot-templates="projectSettings.shotTemplates"
                :is-saving="isSavingSettings"
                @save="handleSaveTaskTemplates"
                @cancel="loadProjectSettings"
                @edit-custom-task-type="handleEditCustomTaskType"
                @delete-custom-task-type="handleDeleteCustomTaskType"
              />
            </div>
          </div>
        </TabsContent>

        <!-- Upload Location Tab -->
        <TabsContent value="storage" class="mt-6">
          <div class="bg-card rounded-lg border p-6">
            <UploadLocationConfig
              :initial-location="projectSettings.uploadLocation"
              :is-saving="isSavingSettings"
              @save="handleSaveUploadLocation"
              @cancel="loadProjectSettings"
            />
          </div>
        </TabsContent>
      </Tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { 
  AlertCircle, ArrowLeft, Settings, Cog, Users, Film, 
  ListChecks, FolderOpen 
} from "lucide-vue-next";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useProjectsStore } from "@/stores/projects";
import { useAuthStore } from "@/stores/auth";
import { useToast } from "@/components/ui/toast/use-toast";
import TechnicalSpecsManager from "@/components/project/TechnicalSpecsManager.vue";
import ProjectEditForm from "@/components/project/ProjectEditForm.vue";
import ProjectMemberManagement from "@/components/project/ProjectMemberManagement.vue";
import ProjectThumbnailUpload from "@/components/project/ProjectThumbnailUpload.vue";
import EpisodeManagementSection from "@/components/settings/EpisodeManagementSection.vue";
import CustomTaskStatusManager from "@/components/settings/CustomTaskStatusManager.vue";
import CustomTaskTypeManager from "@/components/settings/CustomTaskTypeManager.vue";
import DefaultTaskTemplatesEditor from "@/components/settings/DefaultTaskTemplatesEditor.vue";
import UploadLocationConfig from "@/components/settings/UploadLocationConfig.vue";
import { projectService } from "@/services/project";
import type { Project } from "@/stores/projects";

const route = useRoute();
const router = useRouter();
const projectsStore = useProjectsStore();
const authStore = useAuthStore();
const { toast } = useToast();

// State
const isLoadingProject = ref(false);
const projectError = ref<string | null>(null);
const project = ref<Project | null>(null);
const activeTab = ref("general");
const isSavingSettings = ref(false);
const taskTemplatesEditorRef = ref<InstanceType<typeof DefaultTaskTemplatesEditor> | null>(null);
const customTaskTypeManagerRef = ref<InstanceType<typeof CustomTaskTypeManager> | null>(null);

// Project settings state
const projectSettings = ref({
  uploadLocation: '',
  assetTemplates: {
    characters: ['modeling', 'surfacing', 'rigging'],
    props: ['modeling', 'surfacing'],
    sets: ['modeling', 'surfacing'],
    vehicles: ['modeling', 'surfacing', 'rigging']
  },
  shotTemplates: ['layout', 'animation', 'simulation', 'lighting', 'compositing']
});

// Computed properties
const projectId = computed(() => parseInt(route.params.projectId as string));

const userDepartment = computed(() => {
  if (!project.value?.project_members || !authStore.user) return undefined;

  const member = project.value.project_members.find(
    (m) => m.user_id === authStore.user?.id
  );
  return member?.department_role;
});

const canManageProject = computed(() => {
  if (!authStore.user) return false;
  return authStore.user.role === 'coordinator' || authStore.user.is_admin;
});

// Methods
const loadProject = async () => {
  try {
    isLoadingProject.value = true;
    projectError.value = null;

    // Try to get project from store first
    let projectData = projectsStore.getProjectById(projectId.value);

    if (!projectData || projectData.id === 0) {
      // Fetch project with members to get user's department role
      projectData = await projectsStore.getProject(projectId.value, true);
    }

    if (!projectData || projectData.id === 0) {
      throw new Error("Project not found");
    }

    project.value = projectData;
    
    // Load project settings
    await loadProjectSettings();
  } catch (error) {
    console.error("Failed to load project:", error);
    projectError.value =
      error instanceof Error ? error.message : "Failed to load project";
  } finally {
    isLoadingProject.value = false;
  }
};

const loadProjectSettings = async () => {
  try {
    // Load project-specific settings from backend
    const settings = await projectService.getProjectSettings(projectId.value);
    
    if (settings) {
      projectSettings.value = {
        uploadLocation: settings.upload_data_location || '',
        assetTemplates: settings.asset_task_templates || projectSettings.value.assetTemplates,
        shotTemplates: settings.shot_task_templates || projectSettings.value.shotTemplates
      };
    }
  } catch (error) {
    console.error("Failed to load project settings:", error);
    // Use default settings if loading fails
  }
};

const handleProjectUpdate = (updatedProject: Project) => {
  project.value = updatedProject;
  // Update the project in the store as well
  projectsStore.updateProjectInStore(updatedProject);
};

const handleThumbnailUpdated = async (thumbnailUrl: string) => {
  if (project.value) {
    project.value.thumbnail_url = thumbnailUrl;
    // Update the project in the store
    projectsStore.updateProjectInStore(project.value);
  }
};

const handleThumbnailRemoved = () => {
  if (project.value) {
    project.value.thumbnail_url = null;
    // Update the project in the store
    projectsStore.updateProjectInStore(project.value);
  }
};

const handleSaveTaskTemplates = async (data: { 
  assetTemplates: any; 
  shotTemplates: string[] 
}) => {
  try {
    isSavingSettings.value = true;
    
    await projectService.updateProjectSettings(projectId.value, {
      asset_task_templates: data.assetTemplates,
      shot_task_templates: data.shotTemplates
    });
    
    projectSettings.value.assetTemplates = data.assetTemplates;
    projectSettings.value.shotTemplates = data.shotTemplates;
    
    toast({
      title: 'Task templates updated',
      description: 'Default task templates have been saved successfully.'
    });
  } catch (error) {
    console.error("Failed to save task templates:", error);
    toast({
      title: 'Error',
      description: error instanceof Error ? error.message : 'Failed to save task templates',
      variant: 'destructive'
    });
  } finally {
    isSavingSettings.value = false;
  }
};

const handleSaveUploadLocation = async (location: string) => {
  try {
    isSavingSettings.value = true;
    
    await projectService.updateProjectSettings(projectId.value, {
      upload_data_location: location
    });
    
    projectSettings.value.uploadLocation = location;
    
    toast({
      title: 'Upload location updated',
      description: 'Upload data location has been saved successfully.'
    });
  } catch (error) {
    console.error("Failed to save upload location:", error);
    toast({
      title: 'Error',
      description: error instanceof Error ? error.message : 'Failed to save upload location',
      variant: 'destructive'
    });
  } finally {
    isSavingSettings.value = false;
  }
};

const handleTaskStatusesUpdated = async () => {
  // Reload project settings when task statuses are updated
  await loadProjectSettings();
  
  toast({
    title: 'Task statuses updated',
    description: 'Task status changes have been saved successfully.'
  });
};

const handleTaskTypesUpdated = async () => {
  // Refresh task types in the task templates editor
  if (taskTemplatesEditorRef.value) {
    await taskTemplatesEditorRef.value.refreshTaskTypes();
  }
  // Reload project settings to refresh task templates with new custom types
  await loadProjectSettings();
};

const handleEditCustomTaskType = (taskType: string, category: 'asset' | 'shot') => {
  // Switch to the tasks tab if not already there
  if (activeTab.value !== 'tasks') {
    activeTab.value = 'tasks';
  }
  // Open the edit dialog in the CustomTaskTypeManager
  if (customTaskTypeManagerRef.value) {
    customTaskTypeManagerRef.value.openEditDialog(category, taskType);
  }
};

const handleDeleteCustomTaskType = (taskType: string, category: 'asset' | 'shot') => {
  // Switch to the tasks tab if not already there
  if (activeTab.value !== 'tasks') {
    activeTab.value = 'tasks';
  }
  // Open the delete dialog in the CustomTaskTypeManager
  if (customTaskTypeManagerRef.value) {
    customTaskTypeManagerRef.value.handleDelete(category, taskType);
  }
};

// Lifecycle
onMounted(() => {
  loadProject();
});
</script>