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

import React, { useState, useEffect } from 'react';
import { 
  Crown, 
  Users, 
  Settings, 
  FolderOpen,
  Shield,
  UserPlus,
  Trash2,
  BarChart3,
  Eye,
  Download,
  HardDrive,
  UserCog,
  Loader2,
  Edit2,
  Check,
  ChevronsUpDown
} 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { useSession } from 'next-auth/react';
import { getUsersForFilter } from '@/lib/gtc-contract/service';
import { cn } from '@/lib/utils';

interface ProjectDashboardProps {
  projectId: string;
}

interface ProjectStats {
  files: {
    totalFiles: number;
    totalSize: number;
    publicFiles: number;
    restrictedFiles: number;
    confidentialFiles: number;
  };
  members: {
    totalMembers: number;
    admins: number;
    editors: number;
    viewers: number;
  };
  activity: {
    views: number;
    downloads: number;
    uploads: number;
    uniqueUsers: number;
  };
}

interface User {
  id: number;
  name: string;
  email: string;
  domain?: string; // 'partners' | 'internal' etc
}

export function ProjectDashboard({ projectId }: ProjectDashboardProps) {
  const { data: session } = useSession();
  const [isOwner, setIsOwner] = useState(false);
  const [projectRole, setProjectRole] = useState<string>('viewer');
  const [stats, setStats] = useState<ProjectStats | null>(null);
  const [members, setMembers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Dialog states
  const [addMemberOpen, setAddMemberOpen] = useState(false);
  const [transferOwnershipOpen, setTransferOwnershipOpen] = useState(false);
  const [deleteProjectOpen, setDeleteProjectOpen] = useState(false);
  const [newOwnerId, setNewOwnerId] = useState('');
  const [deleteConfirmText, setDeleteConfirmText] = useState('');
  
  // User selection related states
  const [availableUsers, setAvailableUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [userSearchTerm, setUserSearchTerm] = useState('');
  const [userPopoverOpen, setUserPopoverOpen] = useState(false);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [isExternalUser, setIsExternalUser] = useState(false);
  const [newMemberRole, setNewMemberRole] = useState<string>('viewer');
  
  const { toast } = useToast();

  // Fetch project info and permissions
  useEffect(() => {
    const fetchProjectData = async () => {
      try {
        // Check permissions
        const accessRes = await fetch(`/api/projects/${projectId}/access`);
        const accessData = await accessRes.json();
        setIsOwner(accessData.isOwner);
        setProjectRole(accessData.role);

        // Get stats if owner
        if (accessData.isOwner) {
          const statsRes = await fetch(`/api/projects/${projectId}/stats`);
          const statsData = await statsRes.json();
          setStats(statsData);
        }

        // Get member list
        const membersRes = await fetch(`/api/projects/${projectId}/members`);
        const membersData = await membersRes.json();
        setMembers(membersData.member);

      } catch (error) {
        console.error('Failed to load project data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchProjectData();
  }, [projectId]);

  // Fetch user list when dialog opens
  useEffect(() => {
    if (addMemberOpen) {
      fetchAvailableUsers();
    } else {
      // Reset when dialog closes
      setSelectedUser(null);
      setUserSearchTerm('');
      setNewMemberRole('viewer');
      setIsExternalUser(false);
    }
  }, [addMemberOpen]);

  const fetchAvailableUsers = async () => {
    try {
      setLoadingUsers(true);
      const users = await getUsersForFilter();
      // Exclude members already in project
      const memberUserIds = members.map(m => m.userId);
      const filteredUsers = users.filter(u => !memberUserIds.includes(u.id));
      setAvailableUsers(filteredUsers);
    } catch (error) {
      console.error('Failed to load user list:', error);
      toast({
        title: 'Error',
        description: 'Unable to load user list.',
        variant: 'destructive',
      });
    } finally {
      setLoadingUsers(false);
    }
  };

  // Add member
  const handleAddMember = async () => {
    if (!selectedUser) {
      toast({
        title: 'Error',
        description: 'Please select a user.',
        variant: 'destructive',
      });
      return;
    }

    try {
      const response = await fetch(`/api/projects/${projectId}/members`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: selectedUser.id,
          role: newMemberRole,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to add member');
      }

      toast({
        title: 'Success',
        description: 'New member has been added.',
      });

      setAddMemberOpen(false);
      // Refresh member list
      const membersRes = await fetch(`/api/projects/${projectId}/members`);
      const membersData = await membersRes.json();
      setMembers(membersData.member);
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to add member.',
        variant: 'destructive',
      });
    }
  };

  // Transfer ownership
  const handleTransferOwnership = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/transfer-ownership`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          newOwnerId: newOwnerId,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to transfer ownership');
      }

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

      setTransferOwnershipOpen(false);
      setIsOwner(false);
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to transfer ownership.',
        variant: 'destructive',
      });
    }
  };

  // Delete project
  const handleDeleteProject = async () => {
    if (deleteConfirmText !== 'DELETE') {
      toast({
        title: 'Error',
        description: 'Please type DELETE to confirm.',
        variant: 'destructive',
      });
      return;
    }

    try {
      const response = await fetch(`/api/projects/${projectId}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('Failed to delete project');
      }

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

      // 프로젝트 목록 페이지로 리다이렉트
      window.location.href = '/evcp/data-room';
    } catch (error) {
      toast({
        title: 'Error',
        description: 'Failed to delete project.',
        variant: 'destructive',
      });
    }
  };

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const roleConfig = {
    owner: { label: 'Owner', icon: Crown, color: 'text-yellow-500' },
    admin: { label: 'Admin', icon: Shield, color: 'text-blue-500' },
    editor: { label: 'Editor', icon: Edit2, color: 'text-green-500' },
    viewer: { label: 'Viewer', icon: Eye, color: 'text-gray-500' },
  };

  // User search filtering
  const filteredUsers = availableUsers.filter(user =>
    user.name.toLowerCase().includes(userSearchTerm.toLowerCase()) ||
    user.email.toLowerCase().includes(userSearchTerm.toLowerCase())
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center space-y-3">
          <Loader2 className="h-8 w-8 animate-spin text-primary mx-auto" />
          <p className="text-sm text-muted-foreground">Loading project information...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold">Project Dashboard</h1>
          <Badge variant="outline" className="flex items-center gap-1">
            {roleConfig[projectRole as keyof typeof roleConfig].icon && 
              React.createElement(roleConfig[projectRole as keyof typeof roleConfig].icon, {
                className: `h-3 w-3 ${roleConfig[projectRole as keyof typeof roleConfig].color}`
              })
            }
            {roleConfig[projectRole as keyof typeof roleConfig].label}
          </Badge>
        </div>

        {isOwner && (
          <div className="flex gap-2">
            <Button onClick={() => setAddMemberOpen(true)}>
              <UserPlus className="h-4 w-4 mr-2" />
              Add Member
            </Button>
            <Button variant="outline">
              <Settings className="h-4 w-4 mr-2" />
              Settings
            </Button>
          </div>
        )}
      </div>

      {/* Owner-only statistics */}
      {isOwner && stats && (
        <div className="grid grid-cols-4 gap-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Total Files</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.storage.fileCount}</div>
              <p className="text-xs text-muted-foreground mt-1">
                {formatBytes(stats.storage.used)}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Members</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.users.total}</div>
              <div className="flex gap-2 mt-1">
                <span className="text-xs text-muted-foreground">
                  Admins {stats.users.byRole.admins}
                </span>
                <span className="text-xs text-muted-foreground">
                  Editors {stats.users.byRole.editors}
                </span>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Views (30 days)</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.activity.views}</div>
              <p className="text-xs text-muted-foreground mt-1">
                {stats.users.active} active users
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Downloads (30 days)</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.activity.downloads}</div>
              <p className="text-xs text-muted-foreground mt-1">
                {stats.activity.uploads} uploads
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Tab content */}
      <Tabs defaultValue="members">
        <TabsList>
          <TabsTrigger value="members">Members</TabsTrigger>
          {isOwner && (
            <>
              <TabsTrigger value="permissions">Permission Management</TabsTrigger>
              <TabsTrigger value="danger">Danger Zone</TabsTrigger>
            </>
          )}
        </TabsList>

        <TabsContent value="members" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle>Project Members</CardTitle>
              <CardDescription>
                List of users who can access this project
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {members.map((member) => (
                  <div key={member.id} className="flex items-center justify-between p-3 border rounded-lg">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 bg-gray-100 rounded-full flex items-center justify-center">
                        {member.user.name?.charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <p className="font-medium">{member.user.name}</p>
                        <p className="text-sm text-muted-foreground">{member.user.email}</p>
                      </div>
                    </div>
                    <Badge variant="secondary">
                      {roleConfig[member.role as keyof typeof roleConfig].icon && 
                        React.createElement(roleConfig[member.role as keyof typeof roleConfig].icon, {
                          className: `h-3 w-3 mr-1 ${roleConfig[member.role as keyof typeof roleConfig].color}`
                        })
                      }
                      {roleConfig[member.role as keyof typeof roleConfig].label}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {isOwner && (
          <TabsContent value="danger" className="mt-6">
            <Card className="border-red-200">
              <CardHeader>
                <CardTitle className="text-red-600">Danger Zone</CardTitle>
                <CardDescription>
                  These actions cannot be undone. Please proceed with caution.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div>
                    <h3 className="font-medium">Transfer Ownership</h3>
                    <p className="text-sm text-muted-foreground">
                      Transfer project ownership to another member
                    </p>
                  </div>
                  <Button 
                    variant="outline"
                    onClick={() => setTransferOwnershipOpen(true)}
                  >
                    <UserCog className="h-4 w-4 mr-2" />
                    Transfer Ownership
                  </Button>
                </div>

                <div className="flex items-center justify-between p-4 border rounded-lg border-red-200">
                  <div>
                    <h3 className="font-medium text-red-600">Delete Project</h3>
                    <p className="text-sm text-muted-foreground">
                      Permanently delete project and all files
                    </p>
                  </div>
                  <Button 
                    variant="destructive"
                    onClick={() => setDeleteProjectOpen(true)}
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    Delete Project
                  </Button>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        )}
      </Tabs>

      {/* Add Member Dialog */}
      <Dialog open={addMemberOpen} onOpenChange={setAddMemberOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Add Member</DialogTitle>
            <DialogDescription>
              Add a member to the project
            </DialogDescription>
          </DialogHeader>

          <Tabs defaultValue="internal" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="internal">Internal Users</TabsTrigger>
              <TabsTrigger value="external" className="flex items-center gap-2">
                External Users
                <Badge variant="outline" className="ml-1 text-xs">Viewer Only</Badge>
              </TabsTrigger>
            </TabsList>

            <TabsContent value="internal" className="space-y-4 mt-4">
              <div className="space-y-2">
                <Label htmlFor="internal-user">Select User</Label>
                
                {loadingUsers ? (
                  <div className="flex items-center justify-center py-4">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span className="ml-2 text-sm text-muted-foreground">Loading user list...</span>
                  </div>
                ) : (
                  <>
                    <Popover open={userPopoverOpen} onOpenChange={setUserPopoverOpen}>
                      <PopoverTrigger asChild>
                        <Button
                          variant="outline"
                          role="combobox"
                          aria-expanded={userPopoverOpen}
                          className="w-full justify-between"
                        >
                          <span className="truncate">
                            {selectedUser && selectedUser.domain !== 'partners' ? (
                              <div className="text-left">
                                <div className="font-medium">{selectedUser.name}</div>
                                <div className="text-xs text-muted-foreground">{selectedUser.email}</div>
                              </div>
                            ) : (
                              "Select internal user..."
                            )}
                          </span>
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-[460px] p-0">
                        <Command>
                          <CommandInput
                            placeholder="Search by name or email..."
                            value={userSearchTerm}
                            onValueChange={setUserSearchTerm}
                          />
                          <CommandList className="max-h-[300px]">
                            <CommandEmpty>No user found.</CommandEmpty>
                            <CommandGroup heading="Internal User List">
                              {filteredUsers
                                .filter(u => u.domain !== 'partners')
                                .map((user) => (
                                  <CommandItem
                                    key={user.id}
                                    onSelect={() => {
                                      setSelectedUser(user);
                                      setUserPopoverOpen(false);
                                      setIsExternalUser(false);
                                      setNewMemberRole('viewer');
                                    }}
                                    value={`${user.name} ${user.email}`}
                                    className="truncate"
                                  >
                                    <Users className="mr-2 h-4 w-4 text-blue-500 flex-shrink-0" />
                                    <div className="flex-1 truncate">
                                      <div className="font-medium truncate">{user.name}</div>
                                      <div className="text-xs text-muted-foreground truncate">{user.email}</div>
                                    </div>
                                    <Check
                                      className={cn(
                                        "ml-2 h-4 w-4 flex-shrink-0",
                                        selectedUser?.id === user.id && !isExternalUser ? "opacity-100" : "opacity-0"
                                      )}
                                    />
                                  </CommandItem>
                                ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>

                    <p className="text-xs text-muted-foreground">
                      Internal users can be assigned any role.
                    </p>
                  </>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="internal-role">Role</Label>
                <Select 
                  value={newMemberRole} 
                  onValueChange={setNewMemberRole}
                  disabled={!selectedUser || isExternalUser}
                >
                  <SelectTrigger id="internal-role">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="viewer">Viewer - Read only</SelectItem>
                    <SelectItem value="editor">Editor - Can edit files</SelectItem>
                    <SelectItem value="admin">Admin - Project management</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </TabsContent>

            <TabsContent value="external" className="space-y-4 mt-4">
              <div className="rounded-lg bg-amber-50 border border-amber-200 p-3 mb-4">
                <p className="text-sm text-amber-800">
                  <strong>Security Policy Notice</strong><br/>
                  External users (partners) can only be granted Viewer permissions due to security policy.
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="external-user">Select Partner</Label>
                
                {loadingUsers ? (
                  <div className="flex items-center justify-center py-4">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span className="ml-2 text-sm text-muted-foreground">Loading user list...</span>
                  </div>
                ) : (
                  <Popover open={userPopoverOpen} onOpenChange={setUserPopoverOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={userPopoverOpen}
                        className="w-full justify-between"
                      >
                        <span className="truncate">
                          {selectedUser && selectedUser.domain === 'partners' ? (
                            <span className="flex items-center gap-2">
                              {selectedUser.name}
                              <Badge variant="outline" className="ml-1 text-xs">External</Badge>
                            </span>
                          ) : (
                            "Select external user..."
                          )}
                        </span>
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[460px] p-0">
                      <Command>
                        <CommandInput
                          placeholder="Search by name..."
                          value={userSearchTerm}
                          onValueChange={setUserSearchTerm}
                        />
                        <CommandList className="max-h-[300px]">
                          <CommandEmpty>No external users found.</CommandEmpty>
                          <CommandGroup heading="Partner List">
                            {filteredUsers
                              .filter(u => u.domain === 'partners')
                              .map((user) => (
                                <CommandItem
                                  key={user.id}
                                  onSelect={() => {
                                    setSelectedUser(user);
                                    setUserPopoverOpen(false);
                                    setIsExternalUser(true);
                                    setNewMemberRole('viewer');
                                  }}
                                  value={user.name}
                                  className="truncate"
                                >
                                  <Users className="mr-2 h-4 w-4 text-amber-600" />
                                  <span className="truncate flex-1">{user.name}</span>
                                  <Badge variant="outline" className="text-xs mx-2">External</Badge>
                                  <Check
                                    className={cn(
                                      "ml-auto h-4 w-4 flex-shrink-0",
                                      selectedUser?.id === user.id && isExternalUser ? "opacity-100" : "opacity-0"
                                    )}
                                  />
                                </CommandItem>
                              ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="external-role">Role</Label>
                <Select value="viewer" disabled>
                  <SelectTrigger id="external-role" className="opacity-60">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="viewer">Viewer - Read Only (Fixed)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </TabsContent>
          </Tabs>

          <DialogFooter>
            <Button 
              variant="outline" 
              onClick={() => {
                setAddMemberOpen(false);
                setSelectedUser(null);
                setUserSearchTerm('');
                setNewMemberRole('viewer');
                setIsExternalUser(false);
              }}
            >
              Cancel
            </Button>
            <Button 
              onClick={handleAddMember} 
              disabled={!selectedUser}
            >
              Add
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Transfer Ownership Dialog */}
      <Dialog open={transferOwnershipOpen} onOpenChange={setTransferOwnershipOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Transfer Ownership</DialogTitle>
            <DialogDescription className="text-red-600">
              Warning: This action is irreversible. All permissions will be transferred to the new owner.
            </DialogDescription>
          </DialogHeader>
          
          <div>
            <Label htmlFor="new-owner">Select New Owner</Label>
            <Select value={newOwnerId} onValueChange={setNewOwnerId}>
              <SelectTrigger>
                <SelectValue placeholder="Choose member" />
              </SelectTrigger>
              <SelectContent>
                {members
                  .filter(m => m.role !== 'owner')
                  .map(member => (
                    <SelectItem key={member.userId} value={member.userId.toString()}>
                      {member.user.name} ({member.user.email})
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>
          
          <DialogFooter>
            <Button variant="outline" onClick={() => setTransferOwnershipOpen(false)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleTransferOwnership}>
              Transfer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Project Dialog */}
      <Dialog open={deleteProjectOpen} onOpenChange={(open) => {
        setDeleteProjectOpen(open);
        if (!open) setDeleteConfirmText('');
      }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="text-red-600">Delete Project</DialogTitle>
            <DialogDescription>
              This action cannot be undone. This will permanently delete the project and all associated files.
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            <div className="rounded-lg bg-red-50 border border-red-200 p-4">
              <h4 className="font-semibold text-red-800 mb-2">Warning</h4>
              <ul className="text-sm text-red-700 space-y-1 list-disc list-inside">
                <li>All files will be permanently deleted</li>
                <li>All project members will lose access</li>
                <li>All sharing links will be invalidated</li>
                <li>This action cannot be reversed</li>
              </ul>
            </div>

            <div className="space-y-2">
              <Label htmlFor="delete-confirm">
                Type <span className="font-mono font-bold">DELETE</span> to confirm
              </Label>
              <Input
                id="delete-confirm"
                placeholder="DELETE"
                value={deleteConfirmText}
                onChange={(e) => setDeleteConfirmText(e.target.value)}
                className="font-mono"
              />
            </div>
          </div>
          
          <DialogFooter>
            <Button 
              variant="outline" 
              onClick={() => {
                setDeleteProjectOpen(false);
                setDeleteConfirmText('');
              }}
            >
              Cancel
            </Button>
            <Button 
              variant="destructive" 
              onClick={handleDeleteProject}
              disabled={deleteConfirmText !== 'DELETE'}
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Delete Project
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}