"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Loader2, Save, FolderOpen, AlertCircle } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { db, auth } from "@/lib/firebase/config";
import { doc, getDoc, updateDoc, serverTimestamp } from "firebase/firestore";
import { toast } from "sonner";
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@/components/ui/alert";

interface Project {
  id: string;
  name: string;
  productName: string;
  productVision?: string;
  workspacePath?: string;
  workspaceName?: string;
  githubRepo?: string;
  chatgptUrl?: string;
  projectType: string;
  status: string;
}

export default function ProjectSettingsPage() {
  const params = useParams();
  const router = useRouter();
  const projectId = params.projectId as string;
  const workspace = params.workspace as string;
  
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [orphanedSessionsCount, setOrphanedSessionsCount] = useState(0);
  
  // Form state
  const [productName, setProductName] = useState("");
  const [productVision, setProductVision] = useState("");
  const [workspacePath, setWorkspacePath] = useState("");

  useEffect(() => {
    const fetchProject = async () => {
      try {
        const user = auth.currentUser;
        if (!user) {
          toast.error('Please sign in');
          router.push('/auth');
          return;
        }

        const projectDoc = await getDoc(doc(db, 'projects', projectId));
        if (!projectDoc.exists()) {
          toast.error('Project not found');
          router.push(`/${workspace}/projects`);
          return;
        }

        const projectData = projectDoc.data() as Project;
        setProject({ ...projectData, id: projectDoc.id });
        
        // Set form values
        setProductName(projectData.productName);
        setProductVision(projectData.productVision || "");
        setWorkspacePath(projectData.workspacePath || "");

        // Check for orphaned sessions from old workspace path
        if (projectData.workspacePath) {
          // This would require checking sessions - we'll implement this in the API
          // For now, just show the UI
        }
      } catch (err: any) {
        console.error('Error fetching project:', err);
        toast.error('Failed to load project');
      } finally {
        setLoading(false);
      }
    };

    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        fetchProject();
      } else {
        router.push('/auth');
      }
    });

    return () => unsubscribe();
  }, [projectId, workspace, router]);

  const handleSave = async () => {
    setSaving(true);
    try {
      const user = auth.currentUser;
      if (!user) {
        toast.error('Please sign in');
        return;
      }

      // Get the directory name from the path
      const workspaceName = workspacePath ? workspacePath.split('/').pop() || '' : '';

      await updateDoc(doc(db, 'projects', projectId), {
        productName,
        productVision,
        workspacePath,
        workspaceName,
        updatedAt: serverTimestamp(),
      });

      toast.success('Project settings saved!');
      
      // Refresh project data
      const projectDoc = await getDoc(doc(db, 'projects', projectId));
      if (projectDoc.exists()) {
        setProject({ ...projectDoc.data() as Project, id: projectDoc.id });
      }
    } catch (error) {
      console.error('Error saving project:', error);
      toast.error('Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const handleSelectDirectory = async () => {
    try {
      // Check if File System Access API is supported
      if ('showDirectoryPicker' in window) {
        const dirHandle = await (window as any).showDirectoryPicker({
          mode: 'read',
        });
        
        if (dirHandle?.name) {
          // Provide a path hint (browsers don't expose full paths for security)
          const pathHint = `~/projects/${dirHandle.name}`;
          setWorkspacePath(pathHint);
          
          toast.info('Update the path to match your actual folder location', {
            description: 'You can get the full path from Finder/Explorer or your terminal'
          });
        }
      } else {
        toast.error('Directory picker not supported in this browser', {
          description: 'Please enter the path manually or use Chrome/Edge'
        });
      }
    } catch (error: any) {
      // User cancelled or denied permission
      if (error.name !== 'AbortError') {
        console.error('Error selecting directory:', error);
        toast.error('Failed to select directory');
      }
    }
  };

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

  if (!project) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-muted-foreground">Project not found</p>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col overflow-auto">
      {/* Header */}
      <div className="border-b px-6 py-4">
        <h1 className="text-2xl font-bold">Project Settings</h1>
        <p className="text-sm text-muted-foreground mt-1">
          Manage your project configuration and workspace settings
        </p>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="mx-auto max-w-4xl space-y-6">
          
          {/* General Settings */}
          <Card>
            <CardHeader>
              <CardTitle>General Information</CardTitle>
              <CardDescription>
                Basic details about your project
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="productName">Product Name</Label>
                <Input
                  id="productName"
                  value={productName}
                  onChange={(e) => setProductName(e.target.value)}
                  placeholder="My Awesome Product"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="productVision">Product Vision</Label>
                <Textarea
                  id="productVision"
                  value={productVision}
                  onChange={(e) => setProductVision(e.target.value)}
                  placeholder="Describe what you're building and who it's for..."
                  rows={4}
                />
              </div>
            </CardContent>
          </Card>

          {/* Workspace Settings */}
          <Card>
            <CardHeader>
              <CardTitle>Workspace Path</CardTitle>
              <CardDescription>
                The local directory where you're coding this project
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Why update this?</AlertTitle>
                <AlertDescription>
                  If you renamed your project folder or moved it to a different location, 
                  update the path here so Vibn can correctly track your coding sessions.
                </AlertDescription>
              </Alert>

              <div className="space-y-2">
                <Label htmlFor="workspacePath">Local Workspace Path</Label>
                <div className="flex gap-2">
                  <Input
                    id="workspacePath"
                    value={workspacePath}
                    onChange={(e) => setWorkspacePath(e.target.value)}
                    placeholder="/Users/you/projects/my-project"
                    className="flex-1"
                  />
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleSelectDirectory}
                  >
                    <FolderOpen className="h-4 w-4" />
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">
                  💡 <strong>Tip:</strong> Right-click your project folder → Get Info (Mac) or Properties (Windows) to copy the full path
                </p>
              </div>

              {project.workspacePath && workspacePath !== project.workspacePath && (
                <Alert className="border-orange-500/50 bg-orange-500/10">
                  <AlertCircle className="h-4 w-4 text-orange-600" />
                  <AlertTitle>Path Changed</AlertTitle>
                  <AlertDescription>
                    You're changing the workspace path from <code className="text-xs bg-muted px-1 py-0.5 rounded">{project.workspacePath}</code> to <code className="text-xs bg-muted px-1 py-0.5 rounded">{workspacePath}</code>.
                    <br /><br />
                    After saving, Vibn will track sessions from the new path. Any existing sessions from the old path will remain associated with this project.
                  </AlertDescription>
                </Alert>
              )}
            </CardContent>
          </Card>

          {/* Connected Services */}
          <Card>
            <CardHeader>
              <CardTitle>Connected Services</CardTitle>
              <CardDescription>
                External integrations for this project
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <p className="font-medium">GitHub Repository</p>
                  <p className="text-sm text-muted-foreground">
                    {project.githubRepo || 'Not connected'}
                  </p>
                </div>
                {project.githubRepo && (
                  <a 
                    href={`https://github.com/${project.githubRepo}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-blue-600 hover:underline"
                  >
                    View on GitHub →
                  </a>
                )}
              </div>

              <div className="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <p className="font-medium">ChatGPT Project</p>
                  <p className="text-sm text-muted-foreground">
                    {project.chatgptUrl ? 'Connected' : 'Not connected'}
                  </p>
                </div>
                {project.chatgptUrl && (
                  <a 
                    href={project.chatgptUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-blue-600 hover:underline"
                  >
                    Open ChatGPT →
                  </a>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Save Button */}
          <div className="flex justify-end gap-3 pt-4">
            <Button
              variant="outline"
              onClick={() => router.push(`/${workspace}/project/${projectId}/overview`)}
            >
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                <>
                  <Save className="mr-2 h-4 w-4" />
                  Save Changes
                </>
              )}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

