import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Card from '@/shared/components/ui/Card';
import Button from '@/shared/components/ui/Button';
import Badge from '@/shared/components/ui/Badge';
import Avatar from '@/shared/components/ui/Avatar';
import Spinner from '@/shared/components/ui/Spinner';
import Modal from '@/shared/components/ui/Modal';
import Input from '@/shared/components/ui/Input';
import { useToast } from '@/shared/components/ui/Toast';
import { projectService } from '@/shared/services/projectService';
import { apiClient } from '@/shared/services/apiClient';
import InviteMembersModal from '@/shared/components/modals/InviteMembersModal';
import { TrashIcon, ExclamationTriangleIcon } from '@heroicons/react/24/outline';

export default function ProjectsPage() {
  const [projects, setProjects] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  // Custom Delete Confirmation Modal State
  const [projectToDelete, setProjectToDelete] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // Invite Modal State
  const [invitingProjectId, setInvitingProjectId] = useState(null);

  // Form State
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [dueDate, setDueDate] = useState('');

  const navigate = useNavigate();
  const { addToast } = useToast() || {};

  const fetchProjectsAndUser = async () => {
    try {
      setIsLoading(true);
      setError(null);

      // 1. Fetch current logged-in session user
      const userRes = await apiClient('/auth/me.php').catch(() => null);
      if (userRes?.user) {
        setCurrentUser(userRes.user);
      }

      // 2. Fetch project list
      const data = await projectService.getProjects();
      setProjects(Array.isArray(data) ? data : (data?.data || []));
    } catch (err) {
      console.error('Failed to load projects page data:', err);
      setError(err.message || 'Failed to fetch project list.');
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleCreateProject = async (e) => {
    e.preventDefault();
    if (!name.trim()) {
      addToast?.('Project name is required.', 'error');
      return;
    }

    try {
      setIsSubmitting(true);
      const res = await projectService.createProject({
        name,
        description,
        due_date: dueDate || null,
      });

      addToast?.('Project created successfully!', 'success');
      setIsModalOpen(false);
      setName('');
      setDescription('');
      setDueDate('');

      if (res?.project_id) {
        navigate(`/projects/${res.project_id}/board`);
      } else {
        fetchProjectsAndUser();
      }
    } catch (err) {
      console.error('Failed to create project:', err);
      addToast?.(err.message || 'Failed to create project.', 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Open custom confirmation modal
  const handleOpenDeleteModal = (project, e) => {
    e.stopPropagation(); // Stop navigating to project board
    setProjectToDelete(project);
  };

  // Execute actual deletion API call
  const handleConfirmDelete = async () => {
    if (!projectToDelete) return;

    const { id, name: projectName } = projectToDelete;

    try {
      setIsDeleting(true);

      // Optimistic UI Removal
      setProjects((prev) => prev.filter((p) => p.id !== id));
      setProjectToDelete(null); // Close modal immediately

      await projectService.deleteProject(id);
      addToast?.(`Project "${projectName}" deleted successfully.`, 'success');
    } catch (err) {
      console.error('Failed to delete project:', err);
      addToast?.(err.message || 'Failed to delete project. Ensure you are the owner.', 'error');
      fetchProjectsAndUser(); // Revert state on failure
    } finally {
      setIsDeleting(false);
    }
  };

  const getStatusVariant = (status) => {
    switch (status?.toLowerCase()) {
      case 'completed': return 'emerald';
      case 'in progress':
      case 'active': return 'sky';
      case 'on hold': return 'amber';
      default: return 'slate';
    }
  };

  const currentUserId = currentUser?.id || currentUser?.user_id;

  return (
    <div className="p-8 space-y-6 max-w-7xl mx-auto w-full">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Projects</h1>
          <p className="text-xs text-slate-400 mt-1">
            Manage, track, and collaborate on active workspace projects.
          </p>
        </div>
        <Button onClick={() => setIsModalOpen(true)}>
          + New Project
        </Button>
      </div>

      {/* Loading State */}
      {isLoading && (
        <div className="flex justify-center items-center py-20">
          <Spinner size="lg" />
        </div>
      )}

      {/* Error State */}
      {error && !isLoading && (
        <Card className="border-rose-500/30 bg-rose-500/5 text-rose-300 p-4 text-xs">
          <strong>Error loading projects:</strong> {error}
        </Card>
      )}

      {/* Projects Grid */}
      {!isLoading && !error && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {projects.length === 0 ? (
            <div className="col-span-full py-16 text-center text-slate-400 text-xs border border-dashed border-slate-800 rounded-2xl">
              No projects found. Create your first project to get started!
            </div>
          ) : (
            projects.map((project) => {
              // Fallback to true if owner_id isn't returned so owner can still access delete
              const isOwner = !project.owner_id || Number(currentUserId) === Number(project.owner_id);

              return (
                <Card
                  key={project.id}
                  onClick={() => navigate(`/projects/${project.id}/board`)}
                  className="cursor-pointer hover:border-sky-500/50 transition-all space-y-4 group p-5 bg-[var(--color-surface)] border border-[var(--color-border)] shadow-xl flex flex-col justify-between"
                >
                  <div className="space-y-3">
                    {/* Title & Actions Bar */}
                    <div className="flex items-start justify-between gap-2">
                      <h3 className="font-semibold text-base text-slate-100 group-hover:text-sky-400 transition-colors truncate">
                        {project.name}
                      </h3>
                      <div className="flex items-center gap-1.5 shrink-0">
                        <Badge variant={getStatusVariant(project.status)}>
                          {project.status || 'Active'}
                        </Badge>

                        {/* Invite Button */}
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setInvitingProjectId(project.id);
                          }}
                          className="px-2 py-0.5 bg-sky-500/10 hover:bg-sky-500 text-sky-300 hover:text-white border border-sky-500/30 rounded-md text-[10px] font-medium transition-all flex items-center gap-1 cursor-pointer"
                          title="Invite Members to this Project"
                        >
                          <span>👥</span> Invite
                        </button>

                        {/* Owner-Only Delete Button (Visually styled red trash icon) */}
                        {isOwner && (
                          <button
                            type="button"
                            onClick={(e) => handleOpenDeleteModal(project, e)}
                            className="p-1 rounded-md text-rose-400 bg-rose-500/10 hover:bg-rose-500 hover:text-white border border-rose-500/30 transition shrink-0 cursor-pointer"
                            title="Delete Project"
                          >
                            <TrashIcon className="w-3.5 h-3.5" />
                          </button>
                        )}
                      </div>
                    </div>

                    <p className="text-xs text-slate-400 line-clamp-2 min-h-[2.5rem] leading-relaxed">
                      {project.description || 'No description provided.'}
                    </p>
                  </div>

                  {/* Footer Meta Details */}
                  <div className="pt-3 border-t border-[var(--color-border)] flex items-center justify-between text-xs text-slate-400">
                    <div className="flex items-center gap-2">
                      <Avatar name={project.owner || 'Owner'} size="sm" />
                      <span className="text-[11px] text-slate-300 font-medium truncate max-w-[90px]">
                        {project.owner || 'Unassigned'}
                      </span>
                    </div>

                    {/* Members & Due Date */}
                    <div className="flex items-center gap-3">
                      <span className="flex items-center gap-1 bg-slate-800/80 px-2 py-0.5 rounded-md text-[10px] text-sky-300 border border-slate-700/60" title="Total Members">
                        👤 {project.member_count || 1}
                      </span>
                      <span className="text-[11px]">📅 {project.due_date || 'No due date'}</span>
                    </div>
                  </div>
                </Card>
              );
            })
          )}
        </div>
      )}

      {/* Invite Member Modal */}
      <InviteMembersModal
        isOpen={Boolean(invitingProjectId)}
        onClose={() => setInvitingProjectId(null)}
        projectId={invitingProjectId}
      />

      {/* Create Project Modal */}
      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title="Create New Project"
      >
        <form onSubmit={handleCreateProject} className="space-y-4">
          <Input
            label="Project Name"
            placeholder="e.g. Asana Core Redesign"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />

          <div className="space-y-1">
            <label className="text-xs font-medium text-slate-300">Description</label>
            <textarea
              className="w-full bg-[var(--color-background)] border border-[var(--color-border)] rounded-xl p-3 text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-sky-500 transition-colors min-h-[80px]"
              placeholder="Brief summary of project goals and scope..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>

          <Input
            label="Target Due Date"
            type="date"
            value={dueDate}
            onChange={(e) => setDueDate(e.target.value)}
          />

          <div className="flex justify-end gap-2 pt-3 border-t border-[var(--color-border)]">
            <Button variant="ghost" type="button" onClick={() => setIsModalOpen(false)}>
              Cancel
            </Button>
            <Button type="submit" isLoading={isSubmitting}>
              Create Project
            </Button>
          </div>
        </form>
      </Modal>

      {/* Custom Styled Delete Confirmation Dialog (Replaces window.confirm) */}
      {Boolean(projectToDelete) && (
        <div 
          className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/75 backdrop-blur-sm"
          onClick={() => setProjectToDelete(null)}
        >
          <div 
            className="w-full max-w-md p-6 bg-[#1a212d] border border-slate-800 rounded-2xl shadow-2xl space-y-5"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center gap-3">
              <div className="p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-rose-400 shrink-0">
                <ExclamationTriangleIcon className="w-5 h-5" />
              </div>
              <div>
                <h3 className="text-base font-bold text-white">Delete Project</h3>
                <p className="text-xs text-slate-400 mt-0.5">This action cannot be undone.</p>
              </div>
            </div>

            <p className="text-xs text-slate-300 leading-relaxed bg-slate-900/60 p-3.5 rounded-xl border border-slate-800">
              Are you sure you want to delete <span className="font-semibold text-rose-400">{projectToDelete.name}</span>? 
              All associated tasks, sections, and member permissions will be permanently removed.
            </p>

            <div className="flex items-center justify-end gap-3 pt-2 border-t border-slate-800">
              <Button 
                variant="ghost" 
                type="button" 
                disabled={isDeleting}
                onClick={() => setProjectToDelete(null)}
              >
                Cancel
              </Button>
              <button
                type="button"
                disabled={isDeleting}
                onClick={handleConfirmDelete}
                className="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-xl text-xs font-semibold shadow-lg shadow-rose-600/20 transition cursor-pointer flex items-center gap-2"
              >
                {isDeleting ? 'Deleting...' : 'Yes, Delete Project'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}