'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import { ScopeVersion, ScopeStatus } from '@/lib/types';
import { mockUsers } from '@/lib/mock-data';
import { 
  Plus, 
  Edit, 
  Eye, 
  Archive, 
  Clock, 
  User,
  FileText,
  CheckCircle,
  AlertCircle
} from 'lucide-react';

interface ScopeOfWorkProps {
  projectId: string;
}

// Mock scope data - in real app this would come from API
const mockScopeVersions: ScopeVersion[] = [
  {
    id: '1',
    version: '1.0.0',
    title: 'Initial Project Scope',
    content: '<h2>Project Overview</h2><p>This project aims to develop a comprehensive e-commerce platform with the following key features:</p><ul><li>User authentication and authorization</li><li>Product catalog management</li><li>Shopping cart functionality</li><li>Payment processing integration</li><li>Order management system</li><li>Admin dashboard</li></ul><h2>Technical Requirements</h2><p>The platform will be built using modern web technologies including React, Node.js, and PostgreSQL database.</p>',
    status: 'approved',
    createdBy: '1',
    createdAt: new Date('2024-01-15'),
    updatedAt: new Date('2024-01-15'),
    isActive: false
  },
  {
    id: '2',
    version: '1.1.0',
    title: 'Updated Scope - Mobile Support',
    content: '<h2>Project Overview</h2><p>This project aims to develop a comprehensive e-commerce platform with the following key features:</p><ul><li>User authentication and authorization</li><li>Product catalog management</li><li>Shopping cart functionality</li><li>Payment processing integration</li><li>Order management system</li><li>Admin dashboard</li><li><strong>Mobile responsive design</strong></li><li><strong>Progressive Web App (PWA) capabilities</strong></li></ul><h2>Technical Requirements</h2><p>The platform will be built using modern web technologies including React, Node.js, and PostgreSQL database. Additional mobile optimization will be implemented.</p><h2>Additional Requirements</h2><p>Mobile-first approach with responsive design principles and PWA features for offline functionality.</p>',
    status: 'approved',
    createdBy: '2',
    createdAt: new Date('2024-02-01'),
    updatedAt: new Date('2024-02-01'),
    isActive: false
  },
  {
    id: '3',
    version: '1.2.0',
    title: 'Current Scope - Analytics Integration',
    content: '<h2>Project Overview</h2><p>This project aims to develop a comprehensive e-commerce platform with the following key features:</p><ul><li>User authentication and authorization</li><li>Product catalog management</li><li>Shopping cart functionality</li><li>Payment processing integration</li><li>Order management system</li><li>Admin dashboard</li><li>Mobile responsive design</li><li>Progressive Web App (PWA) capabilities</li><li><strong>Analytics and reporting dashboard</strong></li><li><strong>Customer behavior tracking</strong></li></ul><h2>Technical Requirements</h2><p>The platform will be built using modern web technologies including React, Node.js, and PostgreSQL database. Additional mobile optimization and analytics integration will be implemented.</p><h2>Analytics Requirements</h2><p>Integration with Google Analytics, custom event tracking, and comprehensive reporting dashboard for business insights.</p>',
    status: 'review',
    createdBy: '1',
    createdAt: new Date('2024-02-15'),
    updatedAt: new Date('2024-02-15'),
    isActive: true
  }
];

const getStatusBadgeColor = (status: ScopeStatus) => {
  const colors = {
    draft: 'bg-muted text-foreground border-border',
    review: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    approved: 'bg-green-100 text-green-800 border-green-200',
    archived: 'bg-red-100 text-red-800 border-red-200'
  };
  return colors[status];
};

const getStatusIcon = (status: ScopeStatus) => {
  const icons = {
    draft: FileText,
    review: AlertCircle,
    approved: CheckCircle,
    archived: Archive
  };
  return icons[status];
};

export function ScopeOfWork({ projectId }: ScopeOfWorkProps) {
  const [versions, setVersions] = useState<ScopeVersion[]>(mockScopeVersions);
  const [selectedVersion, setSelectedVersion] = useState<ScopeVersion | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [newScope, setNewScope] = useState({
    title: '',
    content: '',
    status: 'draft' as ScopeStatus
  });

  const activeVersion = versions.find(v => v.isActive);
  const sortedVersions = [...versions].sort((a, b) => 
    new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  );

  const getUserName = (userId: string) => {
    const user = mockUsers.find(u => u.id === userId);
    return user ? user.name : 'Unknown User';
  };

  const generateNextVersion = () => {
    if (versions.length === 0) return '1.0.0';
    
    const latestVersion = versions
      .map(v => v.version)
      .sort((a, b) => {
        const aParts = a.split('.').map(Number);
        const bParts = b.split('.').map(Number);
        for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
          const aDiff = (aParts[i] || 0) - (bParts[i] || 0);
          if (aDiff !== 0) return aDiff;
        }
        return 0;
      })
      .pop();

    if (!latestVersion) return '1.0.0';
    
    const parts = latestVersion.split('.').map(Number);
    parts[2] += 1; // Increment patch version
    return parts.join('.');
  };

  const handleCreateScope = () => {
    const newVersion: ScopeVersion = {
      id: Date.now().toString(),
      version: generateNextVersion(),
      title: newScope.title,
      content: newScope.content,
      status: newScope.status,
      createdBy: '1', // Current user
      createdAt: new Date(),
      updatedAt: new Date(),
      isActive: newScope.status === 'approved'
    };

    // If new version is approved, deactivate others
    if (newScope.status === 'approved') {
      setVersions(prev => prev.map(v => ({ ...v, isActive: false })));
    }

    setVersions(prev => [...prev, newVersion]);
    setNewScope({ title: '', content: '', status: 'draft' });
    setIsCreateDialogOpen(false);
  };

  const handleViewScope = (version: ScopeVersion) => {
    setSelectedVersion(version);
    setIsViewDialogOpen(true);
  };

  const formatDate = (date: Date) => {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${day}/${month}/${year} ${hours}:${minutes}`;
  };

  return (
    <div className="space-y-6">
      {/* Action Button */}
      <div className="flex justify-end">
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm">
              <Plus className="h-4 w-4 mr-2" />
              New Version
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create New Scope Version</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="title">Title</Label>
                  <Input
                    id="title"
                    value={newScope.title}
                    onChange={(e) => setNewScope(prev => ({ ...prev, title: e.target.value }))}
                    placeholder="Enter scope title"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="status">Status</Label>
                  <Select
                    value={newScope.status}
                    onValueChange={(value: ScopeStatus) => setNewScope(prev => ({ ...prev, status: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="review">Under Review</SelectItem>
                      <SelectItem value="approved">Approved</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="content">Content</Label>
                <RichTextEditor
                  value={newScope.content}
                  onChange={(content) => setNewScope(prev => ({ ...prev, content }))}
                  placeholder="Enter scope content..."
                />
              </div>
              <div className="flex justify-end space-x-2">
                <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                  Cancel
                </Button>
                <Button onClick={handleCreateScope}>
                  Create Version {generateNextVersion()}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Active Version */}
      {activeVersion && (
        <div className="p-4 border border-green-200 bg-green-50 rounded-lg">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center space-x-3">
              <Badge className="bg-green-100 text-green-800 border-green-200">
                Active Version {activeVersion.version}
              </Badge>
              <h4 className="font-semibold text-foreground">{activeVersion.title}</h4>
            </div>
            <div className="flex items-center space-x-2">
              <Button variant="outline" size="sm" onClick={() => handleViewScope(activeVersion)}>
                <Eye className="h-4 w-4 mr-1" />
                View
              </Button>
              <Button variant="outline" size="sm">
                <Edit className="h-4 w-4 mr-1" />
                Edit
              </Button>
            </div>
          </div>
          <div className="text-sm text-muted-foreground mb-2">
            Created by {getUserName(activeVersion.createdBy)} on {formatDate(activeVersion.createdAt)}
          </div>
          <div 
            className="prose prose-sm max-w-none text-foreground/80"
            dangerouslySetInnerHTML={{ __html: activeVersion.content.substring(0, 200) + '...' }}
          />
        </div>
      )}

      {/* Version History */}
      <div className="space-y-3">
        <h4 className="font-medium text-foreground">Version History</h4>
        <div className="space-y-2">
          {sortedVersions.slice(0, 3).map((version) => {
            const StatusIcon = getStatusIcon(version.status);
            return (
              <div
                key={version.id}
                className={`p-3 border rounded-lg ${version.isActive ? 'border-green-200 bg-green-50' : 'border-border'}`}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <StatusIcon className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <div className="flex items-center space-x-2">
                        <span className="font-medium text-foreground">v{version.version}</span>
                        <Badge variant="outline" className={getStatusBadgeColor(version.status)}>
                          {version.status.charAt(0).toUpperCase() + version.status.slice(1)}
                        </Badge>
                        {version.isActive && (
                          <Badge className="bg-green-100 text-green-800 border-green-200">
                            Active
                          </Badge>
                        )}
                      </div>
                      <p className="text-sm text-foreground mt-1">{version.title}</p>
                      <div className="flex items-center space-x-4 text-xs text-muted-foreground mt-1">
                        <div className="flex items-center space-x-1">
                          <User className="h-3 w-3" />
                          <span>{getUserName(version.createdBy)}</span>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Clock className="h-3 w-3" />
                          <span>{formatDate(version.createdAt)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button variant="outline" size="sm" onClick={() => handleViewScope(version)}>
                      <Eye className="h-4 w-4 mr-1" />
                      View
                    </Button>
                    {!version.isActive && version.status !== 'archived' && (
                      <Button variant="outline" size="sm">
                        <Edit className="h-4 w-4 mr-1" />
                        Edit
                      </Button>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedVersion && (
                <div className="flex items-center space-x-3">
                  <span>Scope v{selectedVersion.version}</span>
                  <Badge variant="outline" className={getStatusBadgeColor(selectedVersion.status)}>
                    {selectedVersion.status.charAt(0).toUpperCase() + selectedVersion.status.slice(1)}
                  </Badge>
                </div>
              )}
            </DialogTitle>
          </DialogHeader>
          {selectedVersion && (
            <div className="space-y-4">
              <div className="text-sm text-muted-foreground">
                <strong>{selectedVersion.title}</strong> • Created by {getUserName(selectedVersion.createdBy)} on {formatDate(selectedVersion.createdAt)}
              </div>
              <div 
                className="prose prose-sm max-w-none"
                dangerouslySetInnerHTML={{ __html: selectedVersion.content }}
              />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}