// components/project/ProjectList.tsx
'use client';

import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import {
  Plus,
  Folder,
  Users,
  Globe,
  Lock,
  Crown,
  Calendar,
  Search,
  Filter,
  Grid3x3,
  List
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import { useRouter, usePathname } from "next/navigation"

interface Project {
  id: string;
  code: string;
  name: string;
  description?: string;
  isPublic: boolean;
  createdAt: string;
  updatedAt: string;
  role?: string;
  memberCount?: number;
  fileCount?: number;
}

interface ProjectFormData {
  code: string;
  name: string;
  description?: string;
  isPublic: boolean;
}

export function ProjectList() {
  const [projects, setProjects] = useState<{
    owned: Project[];
    member: Project[];
    public: Project[];
  }>({ owned: [], member: [], public: [] });
  const [searchQuery, setSearchQuery] = useState('');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const pathname = usePathname()

  const internal = pathname?.includes('evcp')

  console.log(projects)

  const router = useRouter();
  const { toast } = useToast();

  // React Hook Form setup
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isValid },
    watch,
    setValue,
  } = useForm<ProjectFormData>({
    mode: 'onChange',
    defaultValues: {
      code: '',
      name: '',
      description: '',
      isPublic: false,
    },
  });

  const watchIsPublic = watch('isPublic');

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

// components/project/ProjectList.tsx 의 fetchProjects 함수 수정

const fetchProjects = async () => {
  try {
    const response = await fetch('/api/projects');
    const data = await response.json();
    setProjects(data);
    
    // 멤버인 프로젝트가 정확히 1개일 때 자동 리다이렉트
    const memberProjects = data.member || [];
    const ownedProjects = data.owned || [];
    const totalProjects = [...memberProjects, ...ownedProjects];
    
    if (totalProjects.length === 1) {
      const singleProject = totalProjects[0];
      router.push(`/evcp/data-room/${singleProject.id}/files`);
    }
  } catch (error) {
    toast({
      title: 'Error',
      description: 'Unable to load project list.',
      variant: 'destructive',
    });
  }
};
  const onSubmit = async (data: ProjectFormData) => {
    setIsSubmitting(true);
    try {
      const response = await fetch('/api/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });

      if (!response.ok) throw new Error('Failed to create project');

      const project = await response.json();

      toast({
        title: 'Success',
        description: 'Project has been created.',
      });

      setCreateDialogOpen(false);
      reset();
      fetchProjects();

      // Navigate to created project
      router.push(`/evcp/data-room/${project.id}`);
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to create project.',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDialogClose = (open: boolean) => {
    setCreateDialogOpen(open);
    if (!open) {
      reset();
    }
  };

  const filteredProjects = {
    owned: projects.owned?.filter(p =>
      p.name.toLowerCase().includes(searchQuery.toLowerCase())
    ) || [],  // Return empty array instead of undefined
    member: projects.member?.filter(p =>
      p.name.toLowerCase().includes(searchQuery.toLowerCase())
    ) || [],
    public: projects.public?.filter(p =>
      p.name.toLowerCase().includes(searchQuery.toLowerCase())
    ) || [],
  };


  const ProjectCard = ({ project, role }: { project: Project; role?: string }) => (
    <Card
      className="cursor-pointer hover:shadow-lg transition-shadow"
      onClick={() => router.push(`/evcp/data-room/${project.id}/files`)}
    >
      <CardHeader>
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-2">
            <Folder className="h-5 w-5 text-blue-500" />
            <CardTitle className="text-base">{project.code} {project.name}</CardTitle>
          </div>
          {role === 'owner' && (
            <Crown className="h-4 w-4 text-yellow-500" />
          )}
          {project.isPublic ? (
            <Globe className="h-4 w-4 text-green-500" />
          ) : (
            <Lock className="h-4 w-4 text-gray-500" />
          )}
        </div>
        <CardDescription className="line-clamp-2">
          {project.description || 'No description'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <div className="flex items-center gap-3">
            {project.memberCount && (
              <span className="flex items-center gap-1">
                <Users className="h-3 w-3" />
                {project.memberCount}
              </span>
            )}
            {project.fileCount !== undefined && (
              <span className="flex items-center gap-1">
                <Folder className="h-3 w-3" />
                {project.fileCount}
              </span>
            )}
          </div>
          <span className="flex items-center gap-1">
            <Calendar className="h-3 w-3" />
            {new Date(project.updatedAt).toLocaleDateString()}
          </span>
        </div>
        {role && (
          <Badge variant="secondary" className="mt-2">
            {role}
          </Badge>
        )}
      </CardContent>
    </Card>
  );

  return (
    <>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Projects</h1>
          <p className="text-muted-foreground mt-1">
            Manage files and collaborate with your team
          </p>
        </div>
        {internal &&
          <Button onClick={() => setCreateDialogOpen(true)}>
            <Plus className="h-4 w-4 mr-2" />
            New Project
          </Button>

        }

      </div>

      {/* Search and Filter */}
      <div className="flex items-center gap-3 mb-6">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search projects..."
            className="pl-9"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <Button
          variant="outline"
          size="icon"
          onClick={() => setViewMode(viewMode === 'grid' ? 'list' : 'grid')}
        >
          {viewMode === 'grid' ? <List className="h-4 w-4" /> : <Grid3x3 className="h-4 w-4" />}
        </Button>
      </div>

      {/* Project List */}
      <Tabs defaultValue="owned" className="space-y-6">
        <TabsList>
          {internal &&
            <TabsTrigger value="owned">
              My Projects ({filteredProjects.owned?.length})
            </TabsTrigger>
          }

          <TabsTrigger value="member">
            Joined Projects ({filteredProjects.member?.length})
          </TabsTrigger>
          <TabsTrigger value="public">
            Public Projects ({filteredProjects.public?.length})
          </TabsTrigger>
        </TabsList>

        {/* My Projects Tab */}
        {internal &&
          <TabsContent value="owned">
            {filteredProjects.owned?.length === 0 ? (
              <div className="text-center py-12">
                <Crown className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
                <p className="text-muted-foreground">You don't own any projects</p>
                <Button
                  className="mt-4"
                  onClick={() => setCreateDialogOpen(true)}
                >
                  <Plus className="h-4 w-4 mr-2" />
                  Create your first project
                </Button>
              </div>
            ) : viewMode === 'grid' ? (
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {filteredProjects.owned?.map(project => (
                  <ProjectCard key={project.id} project={project} role="owner" />
                ))}
              </div>
            ) : (
              <div className="space-y-2">
                {filteredProjects.owned?.map(project => (
                  <Card
                    key={project.id}
                    className="cursor-pointer hover:shadow transition-shadow"
                    onClick={() => router.push(`/evcp/data-room/${project.id}/files`)}
                  >
                    <CardContent className="flex items-center justify-between p-4">
                      <div className="flex items-center gap-3">
                        <Folder className="h-5 w-5 text-blue-500" />
                        <div>
                          <p className="font-medium">{project.code} {project.name}</p>
                          <p className="text-sm text-muted-foreground">
                            {project.description || 'No description'}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge variant="secondary">Owner</Badge>
                        {project.isPublic ? (
                          <Globe className="h-4 w-4 text-green-500" />
                        ) : (
                          <Lock className="h-4 w-4 text-gray-500" />
                        )}
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </TabsContent>


        }

        <TabsContent value="member">
          {filteredProjects.member?.length === 0 ? (
            <div className="text-center py-12">
              <Users className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground">You are not a member of any projects</p>
            </div>
          ) : viewMode === 'grid' ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {filteredProjects.member?.map(project => (
                <ProjectCard key={project.id} project={project} role={project.role} />
              ))}
            </div>
          ) : (
            <div className="space-y-2">
              {filteredProjects.member?.map(project => (
                <Card
                  key={project.id}
                  className="cursor-pointer hover:shadow transition-shadow"
                  onClick={() => router.push(`/evcp/data-room/${project.id}/files`)}
                >
                  <CardContent className="flex items-center justify-between p-4">
                    <div className="flex items-center gap-3">
                      <Folder className="h-5 w-5 text-blue-500" />
                      <div>
                        <p className="font-medium">{project.code} {project.name}</p>
                        <p className="text-sm text-muted-foreground">
                          {project.description || 'No description'}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant="secondary">{project.role}</Badge>
                      {project.isPublic ? (
                        <Globe className="h-4 w-4 text-green-500" />
                      ) : (
                        <Lock className="h-4 w-4 text-gray-500" />
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="public">
          {filteredProjects.public?.length === 0 ? (
            <div className="text-center py-12">
              <Globe className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground">No public projects</p>
            </div>
          ) : viewMode === 'grid' ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {filteredProjects.public?.map(project => (
                <ProjectCard key={project.id} project={project} />
              ))}
            </div>
          ) : (
            <div className="space-y-2">
              {filteredProjects.public?.map(project => (
                <Card
                  key={project.id}
                  className="cursor-pointer hover:shadow transition-shadow"
                  onClick={() => router.push(`/evcp/data-room/${project.id}/files`)}
                >
                  <CardContent className="flex items-center justify-between p-4">
                    <div className="flex items-center gap-3">
                      <Globe className="h-5 w-5 text-green-500" />
                      <div>
                        <p className="font-medium">{project.code} {project.name}</p>
                        <p className="text-sm text-muted-foreground">
                          {project.description || 'No description'}
                        </p>
                      </div>
                    </div>
                    <Badge variant="outline">Public</Badge>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

      {/* Create Project Dialog */}
      <Dialog open={createDialogOpen} onOpenChange={handleDialogClose}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create New Project</DialogTitle>
            <DialogDescription>
              Create a new project to share files with your team
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div>
              <Label htmlFor="code">
                Project Code <span className="text-red-500">*</span>
              </Label>
              <Input
                id="code"
                {...register('code', {
                  required: 'Project code is required',
                  minLength: {
                    value: 2,
                    message: 'Project code must be at least 2 characters',
                  },
                  pattern: {
                    value: /^[A-Z0-9]+$/,
                    message: 'Project code can only contain uppercase letters and numbers',
                  },
                })}
                placeholder="SN1001"
                className={errors.code ? 'border-red-500' : ''}
              />
              {errors.code && (
                <p className="text-sm text-red-500 mt-1">{errors.code.message}</p>
              )}
            </div>

            <div>
              <Label htmlFor="name">
                Project Name <span className="text-red-500">*</span>
              </Label>
              <Input
                id="name"
                {...register('name', {
                  required: 'Project name is required',
                  minLength: {
                    value: 2,
                    message: 'Project name must be at least 2 characters',
                  },
                  maxLength: {
                    value: 50,
                    message: 'Project name cannot exceed 50 characters',
                  },
                })}
                placeholder="e.g. FNLG"
                className={errors.name ? 'border-red-500' : ''}
              />
              {errors.name && (
                <p className="text-sm text-red-500 mt-1">{errors.name.message}</p>
              )}
            </div>

            <div>
              <Label htmlFor="description">Description (Optional)</Label>
              <Input
                id="description"
                {...register('description', {
                  maxLength: {
                    value: 200,
                    message: 'Description cannot exceed 200 characters',
                  },
                })}
                placeholder="Brief description of the project"
                className={errors.description ? 'border-red-500' : ''}
              />
              {errors.description && (
                <p className="text-sm text-red-500 mt-1">{errors.description.message}</p>
              )}
            </div>

            <div className="flex items-center justify-between">
              <div>
                <Label htmlFor="public">Public Project</Label>
                <p className="text-sm text-muted-foreground">
                  All users can view this project
                </p>
              </div>
              <Switch
                id="public"
                checked={watchIsPublic}
                onCheckedChange={(checked) => setValue('isPublic', checked)}
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => handleDialogClose(false)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={!isValid || isSubmitting}
              >
                {isSubmitting ? 'Creating...' : 'Create Project'}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  );
}