import { useState, useEffect, useRef, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import {
  ArrowLeft, FolderKanban, CalendarDays, Upload, Paperclip,
  Send, Trash2, Download, MoreHorizontal, Edit, CheckCircle2, FileIcon
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { format } from "date-fns";

const statusBadge: Record<string, string> = {
  active: "bg-emerald-100 text-emerald-700",
  "in-progress": "bg-blue-100 text-blue-700",
  completed: "bg-muted text-muted-foreground",
  "on-hold": "bg-amber-100 text-amber-700",
};

export default function ProjectDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [project, setProject] = useState<any>(null);
  const [comments, setComments] = useState<any[]>([]);
  const [files, setFiles] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [newComment, setNewComment] = useState("");
  const [sending, setSending] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [userProfiles, setUserProfiles] = useState<Record<string, any>>({});
  const [isAdmin, setIsAdmin] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editForm, setEditForm] = useState({ title: "", description: "", status: "active", priority: "medium", budget: "" });

  const fileInputRef = useRef<HTMLInputElement>(null);
  const chatEndRef = useRef<HTMLDivElement>(null);

  const fetchProject = useCallback(async () => {
    if (!id) return;
    const { data } = await supabase
      .from("projects")
      .select("*, associations(name)")
      .eq("id", id)
      .single();
    if (data) setProject(data);
  }, [id]);

  const fetchComments = useCallback(async () => {
    if (!id) return;
    const { data } = await supabase
      .from("project_comments")
      .select("*")
      .eq("project_id", id)
      .order("created_at", { ascending: true });
    setComments(data || []);

    // Fetch profiles for comment authors
    const userIds = [...new Set((data || []).map((c: any) => c.user_id))];
    if (userIds.length > 0) {
      const { data: profiles } = await supabase
        .from("profiles")
        .select("user_id, full_name, email")
        .in("user_id", userIds);
      const map: Record<string, any> = {};
      (profiles || []).forEach((p: any) => { map[p.user_id] = p; });
      setUserProfiles(prev => ({ ...prev, ...map }));
    }
  }, [id]);

  const fetchFiles = useCallback(async () => {
    if (!id) return;
    const { data } = await supabase
      .from("project_files")
      .select("*")
      .eq("project_id", id)
      .order("created_at", { ascending: false });
    setFiles(data || []);
  }, [id]);

  useEffect(() => {
    const init = async () => {
      setLoading(true);
      const { data: { user } } = await supabase.auth.getUser();
      setCurrentUser(user);
      if (user) {
        const { data: roles } = await supabase
          .from("user_roles")
          .select("role")
          .eq("user_id", user.id);
        setIsAdmin((roles || []).some((r: any) => r.role === "admin" || r.role === "manager"));
      }
      await Promise.all([fetchProject(), fetchComments(), fetchFiles()]);
      setLoading(false);
    };
    init();
  }, [fetchProject, fetchComments, fetchFiles]);

  // Realtime subscription for comments
  useEffect(() => {
    if (!id) return;
    const channel = supabase
      .channel(`project-comments-${id}`)
      .on("postgres_changes", {
        event: "*",
        schema: "public",
        table: "project_comments",
        filter: `project_id=eq.${id}`,
      }, () => {
        fetchComments();
      })
      .subscribe();
    return () => { supabase.removeChannel(channel); };
  }, [id, fetchComments]);

  // Auto-scroll chat
  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [comments]);

  const handleSendComment = async () => {
    if (!newComment.trim() || !currentUser || !id) return;
    setSending(true);
    const { error } = await supabase.from("project_comments").insert({
      project_id: id,
      user_id: currentUser.id,
      content: newComment.trim(),
    });
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else setNewComment("");
    setSending(false);
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const uploadFiles = e.target.files;
    if (!uploadFiles || !currentUser || !id) return;
    setUploading(true);

    for (const file of Array.from(uploadFiles)) {
      const filePath = `${id}/${Date.now()}-${file.name}`;
      const { error: uploadError } = await supabase.storage
        .from("project-files")
        .upload(filePath, file);

      if (uploadError) {
        toast({ variant: "destructive", title: "Upload failed", description: uploadError.message });
        continue;
      }

      const { data: urlData } = supabase.storage.from("project-files").getPublicUrl(filePath);

      await supabase.from("project_files").insert({
        project_id: id,
        user_id: currentUser.id,
        file_name: file.name,
        file_url: urlData.publicUrl,
        file_size: file.size,
        mime_type: file.type,
      });

      // Also post a comment about the file
      await supabase.from("project_comments").insert({
        project_id: id,
        user_id: currentUser.id,
        content: `📎 Attached file: ${file.name}`,
      });
    }

    await fetchFiles();
    setUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleDeleteFile = async (fileId: string, fileUrl: string) => {
    // Extract path from URL
    const pathMatch = fileUrl.split("/project-files/")[1];
    if (pathMatch) {
      await supabase.storage.from("project-files").remove([decodeURIComponent(pathMatch)]);
    }
    await supabase.from("project_files").delete().eq("id", fileId);
    toast({ title: "File deleted" });
    fetchFiles();
  };

  const handleMarkComplete = async () => {
    if (!id) return;
    const { error } = await supabase.from("projects").update({ status: "completed" }).eq("id", id);
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else { toast({ title: "Project marked as completed" }); fetchProject(); }
  };

  const openEdit = () => {
    if (!project) return;
    setEditForm({
      title: project.title,
      description: project.description || "",
      status: project.status,
      priority: project.priority || "medium",
      budget: project.budget?.toString() || "",
    });
    setEditOpen(true);
  };

  const handleEditSave = async () => {
    if (!id) return;
    // Non-admins cannot change status to completed
    const payload: any = {
      title: editForm.title,
      description: editForm.description || null,
      priority: editForm.priority,
      budget: editForm.budget ? parseFloat(editForm.budget) : null,
    };
    if (isAdmin) {
      payload.status = editForm.status;
    }
    const { error } = await supabase.from("projects").update(payload).eq("id", id);
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else { toast({ title: "Project updated" }); setEditOpen(false); fetchProject(); }
  };

  const getInitials = (userId: string) => {
    const profile = userProfiles[userId];
    if (profile?.full_name) return profile.full_name.split(" ").map((n: string) => n[0]).join("").toUpperCase().slice(0, 2);
    return "U";
  };

  const getDisplayName = (userId: string) => {
    const profile = userProfiles[userId];
    return profile?.full_name || profile?.email || "Unknown User";
  };

  const isOwner = currentUser?.id === project?.created_by;

  if (loading) {
    return <div className="flex justify-center py-24"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>;
  }

  if (!project) {
    return <div className="text-center text-muted-foreground">Project not found.</div>;
  }

  const basePath = window.location.pathname.startsWith("/client") ? "/client/projects" : "/dashboard/projects";

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      {/* Header */}
      <Button variant="ghost" className="gap-2 -ml-2" onClick={() => navigate(basePath)}>
        <ArrowLeft className="h-4 w-4" /> Back to Projects
      </Button>

      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
        <div className="flex items-start gap-3">
          <FolderKanban className="h-8 w-8 text-primary mt-1" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">{project.title}</h1>
            <div className="flex flex-wrap items-center gap-2 mt-1 text-sm text-muted-foreground">
              <CalendarDays className="h-3.5 w-3.5" />
              <span>Created {format(new Date(project.created_at), "M/d/yyyy")}</span>
              <Badge className={statusBadge[project.status] || "bg-muted text-muted-foreground"} variant="secondary">
                {project.status === "in-progress" ? "In Progress" : project.status?.charAt(0).toUpperCase() + project.status?.slice(1)}
              </Badge>
              {project.associations?.name && (
                <span className="text-primary">{project.associations.name}</span>
              )}
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          {(isAdmin || isOwner) && (
            <Button variant="outline" className="gap-2" onClick={openEdit}>
              <Edit className="h-4 w-4" /> Edit & Assign
            </Button>
          )}
          {isAdmin && project.status !== "completed" && (
            <Button className="gap-2" onClick={handleMarkComplete}>
              <CheckCircle2 className="h-4 w-4" /> Mark Complete
            </Button>
          )}
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Project Details */}
          <Card>
            <CardHeader><CardTitle className="text-base">Project Details</CardTitle></CardHeader>
            <CardContent>
              <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                {project.description || "No description provided."}
              </p>
              {project.budget && (
                <p className="text-sm mt-3"><span className="font-medium">Budget:</span> ${Number(project.budget).toLocaleString()}</p>
              )}
            </CardContent>
          </Card>

          {/* Discussion */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                Project Discussion
                <Badge variant="outline" className="text-xs">Real-time</Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="max-h-[400px] overflow-y-auto space-y-3 pr-1">
                {comments.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-8">No messages yet. Start the conversation!</p>
                ) : (
                  comments.map((c) => {
                    const isMine = c.user_id === currentUser?.id;
                    return (
                      <div key={c.id} className={`flex gap-3 ${isMine ? "flex-row-reverse" : ""}`}>
                        <Avatar className="h-8 w-8 shrink-0">
                          <AvatarFallback className="text-xs bg-primary/10 text-primary">{getInitials(c.user_id)}</AvatarFallback>
                        </Avatar>
                        <div className={`max-w-[75%] ${isMine ? "text-right" : ""}`}>
                          <div className="flex items-center gap-2 mb-0.5">
                            <span className="text-xs font-medium text-foreground">{getDisplayName(c.user_id)}</span>
                            <span className="text-xs text-muted-foreground">
                              {format(new Date(c.created_at), "MMM d, h:mm a")}
                            </span>
                          </div>
                          <div className={`inline-block rounded-lg px-3 py-2 text-sm ${isMine ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
                            {c.content}
                          </div>
                        </div>
                      </div>
                    );
                  })
                )}
                <div ref={chatEndRef} />
              </div>
              <Separator />
              <div className="flex gap-2">
                <Textarea
                  value={newComment}
                  onChange={(e) => setNewComment(e.target.value)}
                  placeholder="Type a message..."
                  className="min-h-[40px] max-h-[120px] resize-none"
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSendComment(); }
                  }}
                />
                <div className="flex flex-col gap-1">
                  <Button size="icon" onClick={handleSendComment} disabled={sending || !newComment.trim()}>
                    <Send className="h-4 w-4" />
                  </Button>
                  <Button size="icon" variant="outline" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
                    <Paperclip className="h-4 w-4" />
                  </Button>
                </div>
              </div>
              <input
                ref={fileInputRef}
                type="file"
                multiple
                className="hidden"
                onChange={handleFileUpload}
              />
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Files */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">Files</CardTitle>
                <Button size="sm" variant="outline" className="gap-1" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
                  <Upload className="h-3.5 w-3.5" /> {uploading ? "Uploading..." : "Upload"}
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {files.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">No files uploaded yet.</p>
              ) : (
                <div className="space-y-2">
                  {files.map((f) => (
                    <div key={f.id} className="flex items-center gap-2 p-2 rounded-md border text-sm group hover:bg-muted/50">
                      {f.mime_type?.startsWith("image/") ? (
                        <img src={f.file_url} alt={f.file_name} className="h-8 w-8 rounded object-cover" />
                      ) : (
                        <FileIcon className="h-5 w-5 text-muted-foreground shrink-0" />
                      )}
                      <div className="flex-1 min-w-0">
                        <p className="truncate font-medium text-xs">{f.file_name}</p>
                        <p className="text-xs text-muted-foreground">
                          {f.file_size ? `${(f.file_size / 1024).toFixed(0)} KB` : ""} · {format(new Date(f.created_at), "MMM d")}
                        </p>
                      </div>
                      <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <a href={f.file_url} target="_blank" rel="noopener noreferrer">
                          <Button size="icon" variant="ghost" className="h-7 w-7"><Download className="h-3.5 w-3.5" /></Button>
                        </a>
                        {(isAdmin || f.user_id === currentUser?.id) && (
                          <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => handleDeleteFile(f.id, f.file_url)}>
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Info */}
          <Card>
            <CardHeader><CardTitle className="text-base">Assignments Info</CardTitle></CardHeader>
            <CardContent className="space-y-3 text-sm">
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase">Association</p>
                <p>{project.associations?.name || "None assigned"}</p>
              </div>
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase">Priority</p>
                <p className="capitalize">{project.priority || "Medium"}</p>
              </div>
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase">Assigned To</p>
                <p>{project.assigned_to || "None assigned"}</p>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Edit Dialog */}
      <Dialog open={editOpen} onOpenChange={setEditOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>Edit Project</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div><Label>Project Name</Label><Input value={editForm.title} onChange={(e) => setEditForm({ ...editForm, title: e.target.value })} /></div>
            <div><Label>Description</Label><Textarea value={editForm.description} onChange={(e) => setEditForm({ ...editForm, description: e.target.value })} rows={3} /></div>
            <div className="grid grid-cols-2 gap-4">
              {isAdmin && (
                <div>
                  <Label>Status</Label>
                  <Select value={editForm.status} onValueChange={(v) => setEditForm({ ...editForm, status: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="in-progress">In Progress</SelectItem>
                      <SelectItem value="completed">Completed</SelectItem>
                      <SelectItem value="on-hold">On Hold</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
              <div>
                <Label>Budget ($)</Label>
                <Input type="number" value={editForm.budget} onChange={(e) => setEditForm({ ...editForm, budget: e.target.value })} />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
            <Button onClick={handleEditSave}>Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
