import React, { useState, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Slider } from "@/components/ui/slider";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Upload, Edit, Mail, Check, X, AlertTriangle, FileVideo, Play, Pause } from 'lucide-react';

const CasesSection = () => {
  const [isWorkflowOpen, setIsWorkflowOpen] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [selectedCase, setSelectedCase] = useState(null);
  const [videoFile, setVideoFile] = useState(null);
  const [videoUrl, setVideoUrl] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [trimStart, setTrimStart] = useState(0);
  const [trimEnd, setTrimEnd] = useState(100);
  
  const videoRef = useRef(null);
  const fileInputRef = useRef(null);

  // Mock data - replace with API calls
  const cases = [
    {
      id: "CASE-001",
      description: "illegal entry into Woodlands Checkpoint",
      priority: "High",
      status: "Pending",
      lastUpdated: "2024-10-26",
      officer: "John Doe"
    },
    {
      id: "CASE-002",
      description: "Trespassing Into Changi Airport",
      priority: "Medium",
      status: "Completed",
      lastUpdated: "2024-10-25",
      officer: "Jane Smith"
    },
    {
      id: "CASE-003",
      description: "Lost Cashcard at Tuas Checkpoint",
      priority: "Medium",
      status: "In Progress",
      lastUpdated: "2024-10-25",
      officer: "Jane Smith"
    },
  ];

  const handleVideoUpload = (event) => {
    const file = event.target.files[0];
    if (file) {
      setVideoFile(file);
      const url = URL.createObjectURL(file);
      setVideoUrl(url);
    }
  };

  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
      setTrimEnd(videoRef.current.duration);
    }
  };

  const handleTimeUpdate = () => {
    if (videoRef.current) {
      setCurrentTime(videoRef.current.currentTime);
      
      // Stop playback if we reach trimEnd
      if (videoRef.current.currentTime >= trimEnd) {
        videoRef.current.pause();
        setIsPlaying(false);
        videoRef.current.currentTime = trimStart;
      }
    }
  };

  const togglePlayPause = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.currentTime = trimStart;
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const formatTime = (timeInSeconds) => {
    const minutes = Math.floor(timeInSeconds / 60);
    const seconds = Math.floor(timeInSeconds % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  const handleTrimChange = (values) => {
    setTrimStart(values[0]);
    setTrimEnd(values[1]);
    if (videoRef.current) {
      videoRef.current.currentTime = values[0];
    }
  };

  const getPriorityColor = (priority) => {
    const colors = {
      High: "bg-red-100 text-red-800",
      Medium: "bg-yellow-100 text-yellow-800",
      Low: "bg-green-100 text-green-800"
    };
    return colors[priority] || "bg-gray-100 text-gray-800";
  };

  const getStatusColor = (status) => {
    const colors = {
      Pending: "bg-yellow-100 text-yellow-800",
      "In Progress": "bg-blue-100 text-blue-800",
      Completed: "bg-green-100 text-green-800",
      Rejected: "bg-red-100 text-red-800"
    };
    return colors[status] || "bg-gray-100 text-gray-800";
  };

  const handleCaseAction = (caseData) => {
    setSelectedCase(caseData);
    setCurrentStep(1);
    setIsWorkflowOpen(true);
  };

  const WorkflowStep1 = () => (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="text-sm font-medium">Case Number</label>
          <p className="text-lg">{selectedCase?.id}</p>
        </div>
        <div>
          <label className="text-sm font-medium">Priority</label>
          <Badge className={getPriorityColor(selectedCase?.priority)}>
            {selectedCase?.priority}
          </Badge>
        </div>
        <div>
          <label className="text-sm font-medium">Status</label>
          <Badge className={getStatusColor(selectedCase?.status)}>
            {selectedCase?.status}
          </Badge>
        </div>
        <div>
          <label className="text-sm font-medium">Officer</label>
          <p className="text-lg">{selectedCase?.officer}</p>
        </div>
      </div>
      <div>
        <label className="text-sm font-medium">Description</label>
        <p className="text-lg">{selectedCase?.description}</p>
      </div>
    </div>
  );

  const WorkflowStep2 = () => (
    <div className="space-y-4">
      <input
        type="file"
        ref={fileInputRef}
        accept="video/*"
        onChange={handleVideoUpload}
        className="hidden"
      />
      <div 
        className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer"
        onClick={() => fileInputRef.current?.click()}
      >
        {!videoFile ? (
          <>
            <FileVideo className="mx-auto h-12 w-12 text-gray-400" />
            <div className="mt-2">
              <Button>
                <Upload className="mr-2 h-4 w-4" /> Upload Video
              </Button>
            </div>
            <p className="text-sm text-gray-500 mt-2">
              Supported formats: MP4, AVI, MOV (max 500MB)
            </p>
          </>
        ) : (
          <div className="space-y-2">
            <p className="font-medium">{videoFile.name}</p>
            <p className="text-sm text-gray-500">
              {(videoFile.size / (1024 * 1024)).toFixed(2)} MB
            </p>
          </div>
        )}
      </div>
    </div>
  );

  const WorkflowStep3 = () => (
    <div className="space-y-4">
      <div className="bg-gray-100 rounded-lg p-4">
        <div className="flex items-center justify-between mb-4">
          <h4 className="font-medium">Video Editor</h4>
          <div className="space-x-2">
            <Button 
              variant="outline" 
              size="sm"
              onClick={togglePlayPause}
            >
              {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
            </Button>
          </div>
        </div>
        
        {videoUrl && (
          <div className="space-y-4">
            <div className="bg-black rounded-lg overflow-hidden">
              <video
                ref={videoRef}
                src={videoUrl}
                className="w-full"
                onLoadedMetadata={handleLoadedMetadata}
                onTimeUpdate={handleTimeUpdate}
              />
            </div>
            
            <div className="space-y-2">
              <div className="flex justify-between text-sm text-gray-500">
                <span>Current: {formatTime(currentTime)}</span>
                <span>Duration: {formatTime(duration)}</span>
              </div>
              
              <div className="py-4">
                <Slider
                  defaultValue={[0, 100]}
                  max={duration}
                  step={0.1}
                  value={[trimStart, trimEnd]}
                  onValueChange={handleTrimChange}
                  className="w-full"
                />
              </div>
              
              <div className="flex justify-between text-sm">
                <span>Trim Start: {formatTime(trimStart)}</span>
                <span>Trim End: {formatTime(trimEnd)}</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  const WorkflowStep4 = () => (
    <div className="space-y-4">
      <div className="space-y-2">
        <label className="text-sm font-medium">Recipient Email</label>
        <Input type="email" placeholder="recipient@example.com" />
      </div>
      <div className="space-y-2">
        <label className="text-sm font-medium">Subject</label>
        <Input type="text" defaultValue={`Video Request: ${selectedCase?.id}`} />
      </div>
      <div className="space-y-2">
        <label className="text-sm font-medium">Message</label>
        <Textarea 
          rows={4}
          defaultValue={`Dear Recipient,\n\nPlease find attached the requested video footage for case ${selectedCase?.id}.\n\nBest regards,\nICA Video Repository Team`}
        />
      </div>
    </div>
  );

  const WorkflowStep5 = () => (
    <div className="space-y-4">
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <h4 className="font-medium text-blue-800 mb-2">Summary</h4>
        <ul className="space-y-2 text-sm text-blue-700">
          <li>Case: {selectedCase?.id}</li>
          <li>Video File: {videoFile?.name}</li>
          <li>Video Size: {videoFile ? (videoFile.size / (1024 * 1024)).toFixed(2) + " MB" : "N/A"}</li>
          <li>Duration: {formatTime(duration)}</li>
          <li>Trim Points: {formatTime(trimStart)} - {formatTime(trimEnd)}</li>
          <li>Recipient: recipient@example.com</li>
        </ul>
      </div>
      <div className="flex space-x-4">
        <Button className="w-full" onClick={() => setIsWorkflowOpen(false)}>
          <Check className="mr-2 h-4 w-4" /> Approve
        </Button>
        <Button variant="destructive" className="w-full">
          <X className="mr-2 h-4 w-4" /> Reject
        </Button>
      </div>
    </div>
  );

  const getCurrentStepContent = () => {
    const steps = {
      1: <WorkflowStep1 />,
      2: <WorkflowStep2 />,
      3: <WorkflowStep3 />,
      4: <WorkflowStep4 />,
      5: <WorkflowStep5 />
    };
    return steps[currentStep];
  };

  const getStepTitle = () => {
    const titles = {
      1: "Case Information",
      2: "Upload Video",
      3: "Edit Video",
      4: "Preview Email",
      5: "Summary & Decision"
    };
    return titles[currentStep];
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <Card>
        <CardHeader>
          <CardTitle>Cases</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Case Number</TableHead>
                  <TableHead>Description</TableHead>
                  <TableHead>Priority</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Last Updated</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {cases.map((caseItem) => (
                  <TableRow key={caseItem.id}>
                    <TableCell className="font-medium">{caseItem.id}</TableCell>
                    <TableCell>{caseItem.description}</TableCell>
                    <TableCell>
                      <Badge className={getPriorityColor(caseItem.priority)}>
                        {caseItem.priority}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(caseItem.status)}>
                        {caseItem.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{caseItem.lastUpdated}</TableCell>
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCaseAction(caseItem)}
                      >
                        Process
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={isWorkflowOpen} onOpenChange={setIsWorkflowOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader className="Review">
            <DialogTitle>{getStepTitle()}</DialogTitle>
          </DialogHeader>
          
          <div className="flex justify-center mb-6">
            <div className="flex items-center">
              {[1, 2, 3, 4, 5].map((step) => (
                <React.Fragment key={step}>
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center ${
                      step === currentStep
                        ? "bg-[#042870] text-white"
                        : step < currentStep
                        ? "bg-green-100 text-green-800"
                        : "bg-gray-100 text-gray-400"
                      }`}
                    >
                      {step < currentStep ? (
                        <Check className="h-4 w-4" />
                      ) : (
                        step
                      )}
                    </div>
                    {step < 5 && (
                      <div
                        className={`w-12 h-0.5 ${
                          step < currentStep ? "bg-green-100" : "bg-gray-100"
                        }`}
                      />
                    )}
                  </React.Fragment>
                ))}
              </div>
            </div>
  
            {getCurrentStepContent()}
  
            <DialogFooter>
              <div className="flex justify-between w-full">
                <Button
                  variant="outline"
                  onClick={() => {
                    // Reset video playback when going back from step 3
                    if (currentStep === 3) {
                      setIsPlaying(false);
                      if (videoRef.current) {
                        videoRef.current.pause();
                        videoRef.current.currentTime = trimStart;
                      }
                    }
                    setCurrentStep(currentStep - 1);
                  }}
                  disabled={currentStep === 1}
                >
                  Previous
                </Button>
                <Button
                  onClick={() => {
                    // Validate before proceeding
                    if (currentStep === 2 && !videoFile) {
                      alert("Please upload a video file before proceeding.");
                      return;
                    }
                    
                    // Reset video playback when moving forward from step 3
                    if (currentStep === 3) {
                      setIsPlaying(false);
                      if (videoRef.current) {
                        videoRef.current.pause();
                        videoRef.current.currentTime = trimStart;
                      }
                    }
                    
                    setCurrentStep(currentStep + 1);
                  }}
                  disabled={currentStep === 5}
                >
                  {currentStep === 4 ? "Review" : "Next"}
                </Button>
              </div>
            </DialogFooter>
          </DialogContent>
        </Dialog>
  
        {/* Cleanup video URL when dialog closes */}
        <Dialog 
          open={isWorkflowOpen} 
          onOpenChange={(open) => {
            if (!open) {
              setIsWorkflowOpen(false);
              if (videoUrl) {
                URL.revokeObjectURL(videoUrl);
                setVideoUrl(null);
              }
              setVideoFile(null);
              setCurrentTime(0);
              setDuration(0);
              setTrimStart(0);
              setTrimEnd(100);
              setIsPlaying(false);
              if (videoRef.current) {
                videoRef.current.pause();
              }
            }
          }}
        >
          <DialogContent className="max-w-2xl">
            {/* ... (previous dialog content remains the same) ... */}
          </DialogContent>
        </Dialog>
      </div>
    );
  };
  
  export default CasesSection;