// // src/pages/Dashboard.jsx
// import React, { useState, useEffect } from 'react';
// import axios from '../api/axiosInstance';
// import './Dashboard.css';

// const Dashboard = () => {
//   const [meetings, setMeetings] = useState([]);
//   const [showCreateForm, setShowCreateForm] = useState(false);
//   const [loading, setLoading] = useState(false);

//   // Form state - simplified to your requirements
//   const [formData, setFormData] = useState({
//     roomName: '',
//     ownerName: '',
//     description: '',
//     scheduledTime: '',
//     validityDuration: 60 // Default 60 minutes
//   });

//   // Fetch existing meetings on component mount
//   useEffect(() => {
//     fetchMeetings();
//   }, []);

//   const fetchMeetings = async () => {
//     try {
//       const response = await axios.get('/meetings');
//       console.log('Fetched meetings:', response.data);
//       setMeetings(response.data.data);
//       console.log('Meetings state updated:', meetings);
//     } catch (error) {
//       console.error('Error fetching meetings:', error);
//     }
//   };

//   const handleInputChange = (e) => {
//     const { name, value } = e.target;
//     setFormData(prev => ({
//       ...prev,
//       [name]: value
//     }));
//   };

//   const handleCreateMeeting = async (e) => {
//     e.preventDefault();
//     setLoading(true);

//     try {
//       // Calculate meeting expiry time
//       const scheduledDate = new Date(formData.scheduledTime);
//       const expiryTime = new Date(scheduledDate.getTime() + (formData.validityDuration * 60 * 1000));

//       const response = await axios.post('/meetings', {
//         title: formData.roomName, // Using roomName as title
//         roomName: formData.roomName,
//         ownerName: formData.ownerName,
//         description: formData.description,
//         scheduledTime: formData.scheduledTime,
//         validityDuration: formData.validityDuration,
//         expiryTime: expiryTime,
//         roomId: `room_${Date.now()}`, // Generate unique room ID
//         status: 'scheduled'
//       });

//       // Add new meeting to the list
//       setMeetings(prev => [response.data, ...prev]);

//       // Reset form
//       setFormData({
//         roomName: '',
//         ownerName: '',
//         description: '',
//         scheduledTime: '',
//         validityDuration: 60
//       });

//       setShowCreateForm(false);
//       alert('Meeting created successfully!');
//     } catch (error) {
//       console.error('Error creating meeting:', error);
//       alert('Failed to create meeting');
//     } finally {
//       setLoading(false);
//     }
//   };

//   const copyMeetingLink = (meeting) => {
//     const meetingLink = `${window.location.origin}/join/${meeting.roomId}?token=${meeting.token}`;
//     navigator.clipboard.writeText(meetingLink);
//     alert('Meeting link copied to clipboard!');
//   };

//   const formatDuration = (minutes) => {
//     if (minutes < 60) {
//       return `${minutes} minutes`;
//     } else {
//       const hours = Math.floor(minutes / 60);
//       const mins = minutes % 60;
//       return mins > 0 ? `${hours}h ${mins}m` : `${hours} hour${hours > 1 ? 's' : ''}`;
//     }
//   };

//   const isExpired = (meeting) => {
//     if (!meeting.expiryTime) return false;
//     return new Date() > new Date(meeting.expiryTime);
//   };

//   return (
//     <div className="dashboard-container">
//       <div className="dashboard-header">
//         <h1>Admin Dashboard</h1>
//         <button
//           className="btn-primary"
//           onClick={() => setShowCreateForm(!showCreateForm)}
//         >
//           {showCreateForm ? 'Cancel' : 'Create New Meeting'}
//         </button>
//       </div>

//       {/* Create Meeting Form */}
//       {showCreateForm && (
//         <div className="create-meeting-form">
//           <h2>Create New Meeting</h2>
//           <form onSubmit={handleCreateMeeting}>
//             <div className="form-group">
//               <label>Room Name</label>
//               <input
//                 type="text"
//                 name="roomName"
//                 value={formData.roomName}
//                 onChange={handleInputChange}
//                 required
//                 placeholder="Enter room name"
//               />
//             </div>

//             <div className="form-group">
//               <label>Owner Name</label>
//               <input
//                 type="text"
//                 name="ownerName"
//                 value={formData.ownerName}
//                 onChange={handleInputChange}
//                 required
//                 placeholder="Enter owner/host name"
//               />
//             </div>

//             <div className="form-group">
//               <label>Description</label>
//               <textarea
//                 name="description"
//                 value={formData.description}
//                 onChange={handleInputChange}
//                 placeholder="Meeting description (optional)"
//                 rows={3}
//               />
//             </div>

//             <div className="form-row">
//               <div className="form-group">
//                 <label>Scheduled Time</label>
//                 <input
//                   type="datetime-local"
//                   name="scheduledTime"
//                   value={formData.scheduledTime}
//                   onChange={handleInputChange}
//                   required
//                 />
//               </div>

//               <div className="form-group">
//                 <label>Meeting Valid For</label>
//                 <select
//                   name="validityDuration"
//                   value={formData.validityDuration}
//                   onChange={handleInputChange}
//                   required
//                 >
//                   <option value={30}>30 minutes</option>
//                   <option value={60}>1 hour</option>
//                   <option value={90}>1.5 hours</option>
//                   <option value={120}>2 hours</option>
//                   <option value={180}>3 hours</option>
//                   <option value={240}>4 hours</option>
//                   <option value={480}>8 hours</option>
//                   <option value={1440}>24 hours</option>
//                 </select>
//               </div>
//             </div>

//             <div className="form-actions">
//               <button type="submit" disabled={loading} className="btn-primary">
//                 {loading ? 'Creating...' : 'Create Meeting'}
//               </button>
//               <button
//                 type="button"
//                 onClick={() => setShowCreateForm(false)}
//                 className="btn-secondary"
//               >
//                 Cancel
//               </button>
//             </div>
//           </form>
//         </div>
//       )}

//       {/* Recent Meetings */}
//       <div className="recent-meetings">
//         <h2>Recent Meetings</h2>
//         <div className="meetings-grid">
//           {meetings.length === 0 ? (
//             <p>No meetings created yet.</p>
//           ) : (
//             meetings.map(meeting => (
//               <div key={meeting._id} className="meeting-card">
//                 <div className="meeting-header">
//                   <h3>{meeting.roomName}</h3>
//                   <span className={`status ${meeting.status} ${isExpired(meeting) ? 'expired' : ''}`}>
//                     {isExpired(meeting) ? 'expired' : meeting.status}
//                   </span>
//                 </div>

//                 <div className="meeting-details">
//                   <p><strong>Owner:</strong> {meeting.ownerName}</p>
//                   <p><strong>Room ID:</strong> {meeting.roomId}</p>
//                   {meeting.description && (
//                     <p><strong>Description:</strong> {meeting.description}</p>
//                   )}
//                   {meeting.scheduledTime && (
//                     <p><strong>Scheduled:</strong> {new Date(meeting.scheduledTime).toLocaleString()}</p>
//                   )}
//                   <p><strong>Valid For:</strong> {formatDuration(meeting.validityDuration)}</p>
//                   {meeting.expiryTime && (
//                     <p><strong>Expires:</strong> {new Date(meeting.expiryTime).toLocaleString()}</p>
//                   )}
//                   <p><strong>Created:</strong> {new Date(meeting.createdAt).toLocaleString()}</p>
//                 </div>

//                 <div className="meeting-actions">
//                   <button
//                     onClick={() => copyMeetingLink(meeting)}
//                     className="btn-copy"
//                     disabled={isExpired(meeting)}
//                   >
//                     {isExpired(meeting) ? 'Expired' : 'Copy Link'}
//                   </button>
//                   <button className="btn-view">
//                     View Details
//                   </button>
//                 </div>
//               </div>
//             ))
//           )}
//         </div>
//       </div>
//     </div>
//   );
// };

// export default Dashboard;

// src/pages/Dashboard.jsx - Simple meeting creation and management

//Workin previus design
// import React, { useState, useEffect } from 'react';
// import axios from '../api/axiosInstance';
// import './Dashboard.css';
// import { useNavigate } from 'react-router-dom';

// const Dashboard = () => {
//   const [meetings, setMeetings] = useState([]);
//   const [showCreateForm, setShowCreateForm] = useState(false);
//   const [loading, setLoading] = useState(false);
//   const navigate = useNavigate();
//   const [formData, setFormData] = useState({
//     roomName: '',
//     ownerName: '',
//     description: '',
//     scheduledTime: '',
//     validityDuration: 60
//   });

//   useEffect(() => {
//     fetchMeetings();
//   }, []);

//   const fetchMeetings = async () => {
//     try {
//       const response = await axios.get('/meetings');
//       console.log('Fetched meetings:', response.data);
//       setMeetings(response.data.data || []);
//     } catch (error) {
//       console.error('Error fetching meetings:', error);
//       alert('Failed to load meetings');
//     }
//   };

//   const handleInputChange = (e) => {
//     const { name, value } = e.target;
//     setFormData(prev => ({ ...prev, [name]: value }));
//   };

//   const handleCreateMeeting = async (e) => {
//     e.preventDefault();

//     if (!formData.roomName || !formData.ownerName || !formData.scheduledTime) {
//       alert('Please fill in all required fields');
//       return;
//     }

//     setLoading(true);

//     try {
//       const response = await axios.post('/meetings', formData);

//       // Add new meeting to list
//       setMeetings(prev => [response.data.data, ...prev]);

//       // Reset form
//       setFormData({
//         roomName: '',
//         ownerName: '',
//         description: '',
//         scheduledTime: '',
//         validityDuration: 60
//       });

//       setShowCreateForm(false);
//       alert('Meeting created successfully!');

//     } catch (error) {
//       console.error('Error creating meeting:', error);
//       alert(error.response?.data?.message || 'Failed to create meeting');
//     } finally {
//       setLoading(false);
//     }
//   };

//   const copyOwnerLink = (meeting) => {
//     navigator.clipboard.writeText(meeting.ownerMeetingUrl);
//     alert('Owner/Moderator link copied! This gives full meeting control.');
//   };

//   const copyParticipantLink = (meeting) => {
//     navigator.clipboard.writeText(meeting.participantMeetingUrl);
//     alert('Participant link copied! This gives standard attendee access.');
//   };

//   // const startMeetingAsOwner = (meeting) => {
//   //   if (isExpired(meeting)) {
//   //     alert('This meeting has expired');
//   //     return;
//   //   }

//   //   navigate(`/meeting?room=${meeting.roomId}&name=${encodeURIComponent(meeting.ownerName)}&token=${meeting.moderatorToken}&role=moderator`);
//   // };

//   // const joinAsParticipant = (meeting) => {
//   //   if (isExpired(meeting)) {
//   //     alert('This meeting has expired');
//   //     return;
//   //   }

//   //   navigate(`/meeting?room=${meeting.roomId}&token=${meeting.participantToken}&role=participant`);
//   // };
//   // const startMeetingAsOwner = (meeting) => {
//   //   if (isExpired(meeting)) {
//   //     alert('This meeting has expired');
//   //     return;
//   //   }

//   //   // Parse the URL to get query parameters
//   //   const url = new URL(meeting.ownerMeetingUrl);
//   //   const searchParams = url.searchParams;

//   //   // Navigate to meeting route with parameters
//   //   navigate(`/meeting?room=${searchParams.get('room')}&name=${searchParams.get('name')}&role=${searchParams.get('role')}`);
//   // };

//   // const joinAsParticipant = (meeting) => {
//   //   if (isExpired(meeting)) {
//   //     alert('This meeting has expired');
//   //     return;
//   //   }

//   //   // Parse the URL to get query parameters
//   //   const url = new URL(meeting.participantMeetingUrl);
//   //   const searchParams = url.searchParams;

//   //   // Navigate to meeting route with parameters
//   //   navigate(`/meeting?room=${searchParams.get('room')}&role=${searchParams.get('role')}`);
//   // };
//   const navigateToMeeting = (meeting, role) => {
//     if (isExpired(meeting)) {
//       alert('This meeting has expired');
//       return;
//     }
//     const token = role === 'moderator' ? meeting.moderatorToken : meeting.participantToken;

//     if (!token) {
//       alert('Authentication token not available. Please refresh and try again.');
//       return;
//     }

//     // Store token in sessionStorage temporarily (secure approach)
//     sessionStorage.setItem('meetingToken', token);
//     sessionStorage.setItem('meetingRole', role);
//     sessionStorage.setItem('meetingId', meeting._id);

//     // Navigate with clean URL (no token in URL)
//     const params = new URLSearchParams({
//       room: meeting.roomId,
//       role: role,
//       ...(role === 'moderator' && { name: meeting.ownerName })
//     });

//     navigate(`/meeting?${params.toString()}`);
//   };

//   const startMeetingAsOwner = (meeting) => {
//     navigateToMeeting(meeting, 'moderator');
//   };

//   const joinAsParticipant = (meeting) => {
//     navigateToMeeting(meeting, 'participant');
//   };

//   const isExpired = (meeting) => {
//     return new Date() > new Date(meeting.expiryTime);
//   };

//   const formatDuration = (minutes) => {
//     if (minutes < 60) return `${minutes} min`;
//     const hours = Math.floor(minutes / 60);
//     const mins = minutes % 60;
//     return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
//   };

//   return (
//     <div className="dashboard-container">
//       {/* Header */}
//       <div className="dashboard-header">
//         <h1>🎥 Meeting Dashboard</h1>
//         <button
//           className="btn-primary"
//           onClick={() => setShowCreateForm(!showCreateForm)}
//         >
//           {showCreateForm ? '✕ Cancel' : '+ Create Meeting'}
//         </button>
//       </div>

//       {/* Create Meeting Form */}
//       {showCreateForm && (
//         <div className="create-form">
//           <h2>Create New Meeting</h2>
//           <form onSubmit={handleCreateMeeting}>
//             <div className="form-row">
//               <div className="form-group">
//                 <label>Meeting Name *</label>
//                 <input
//                   type="text"
//                   name="roomName"
//                   value={formData.roomName}
//                   onChange={handleInputChange}
//                   placeholder="Enter meeting name"
//                   required
//                 />
//               </div>

//               <div className="form-group">
//                 <label>Host/Owner Name *</label>
//                 <input
//                   type="text"
//                   name="ownerName"
//                   value={formData.ownerName}
//                   onChange={handleInputChange}
//                   placeholder="Enter host name"
//                   required
//                 />
//               </div>
//             </div>

//             <div className="form-group">
//               <label>Description (Optional)</label>
//               <textarea
//                 name="description"
//                 value={formData.description}
//                 onChange={handleInputChange}
//                 placeholder="Meeting description"
//                 rows={3}
//               />
//             </div>

//             <div className="form-row">
//               <div className="form-group">
//                 <label>Scheduled Time *</label>
//                 <input
//                   type="datetime-local"
//                   name="scheduledTime"
//                   value={formData.scheduledTime}
//                   onChange={handleInputChange}
//                   required
//                 />
//               </div>

//               <div className="form-group">
//                 <label>Valid Duration *</label>
//                 <select
//                   name="validityDuration"
//                   value={formData.validityDuration}
//                   onChange={handleInputChange}
//                   required
//                 >
//                   <option value={30}>30 minutes</option>
//                   <option value={60}>1 hour</option>
//                   <option value={120}>2 hours</option>
//                   <option value={240}>4 hours</option>
//                   <option value={480}>8 hours</option>
//                   <option value={1440}>24 hours</option>
//                 </select>
//               </div>
//             </div>

//             <div className="form-actions">
//               <button type="submit" disabled={loading} className="btn-create">
//                 {loading ? '🔄 Creating...' : '✅ Create Meeting'}
//               </button>
//             </div>
//           </form>
//         </div>
//       )}

//       {/* Meetings List */}
//       <div className="meetings-section">
//         <h2>📅 Recent Meetings ({meetings.length})</h2>

//         {meetings.length === 0 ? (
//           <div className="no-meetings">
//             <p>No meetings created yet. Create your first meeting!</p>
//           </div>
//         ) : (
//           <div className="meetings-grid">
//             {meetings.map(meeting => (
//               <div key={meeting._id} className={`meeting-card ${isExpired(meeting) ? 'expired' : ''}`}>
//                 <div className="meeting-header">
//                   <h3>🎯 {meeting.roomName}</h3>
//                   <span className={`status ${isExpired(meeting) ? 'expired' : meeting.status}`}>
//                     {isExpired(meeting) ? '⏰ Expired' : `📊 ${meeting.status}`}
//                   </span>
//                 </div>

//                 <div className="meeting-details">
//                   <p><strong>👤 Host:</strong> {meeting.ownerName}</p>
//                   <p><strong>🏷️ Room ID:</strong> <code>{meeting.roomId}</code></p>
//                   {meeting.description && (
//                     <p><strong>📝 Description:</strong> {meeting.description}</p>
//                   )}
//                   <p><strong>📅 Scheduled:</strong> {new Date(meeting.scheduledTime).toLocaleString()}</p>
//                   <p><strong>⏱️ Duration:</strong> {formatDuration(meeting.validityDuration)}</p>
//                   <p><strong>⏰ Expires:</strong> {new Date(meeting.expiryTime).toLocaleString()}</p>
//                 </div>

//                 <div className="meeting-actions">
//                   {!isExpired(meeting) ? (
//                     <>
//                       <button
//                         onClick={() => startMeetingAsOwner(meeting)}
//                         className="btn-owner"
//                         title="Start with moderator privileges"
//                       >
//                         🚀 Start as Host
//                       </button>

//                       <button
//                         onClick={() => joinAsParticipant(meeting)}
//                         className="btn-participant"
//                         title="Join as participant"
//                       >
//                         👥 Join as Guest
//                       </button>

//                       <button
//                         onClick={() => copyOwnerLink(meeting)}
//                         className="btn-copy-owner"
//                         title="Copy host/moderator link"
//                       >
//                         📋 Copy Host Link
//                       </button>

//                       <button
//                         onClick={() => copyParticipantLink(meeting)}
//                         className="btn-copy-participant"
//                         title="Copy participant link"
//                       >
//                         📋 Copy Guest Link
//                       </button>
//                     </>
//                   ) : (
//                     <span className="expired-text">⏰ Meeting has expired</span>
//                   )}
//                 </div>
//               </div>
//             ))}
//           </div>
//         )}
//       </div>
//     </div>
//   );
// };

// export default Dashboard;

import React, { useState, useEffect } from "react";
import axios from "../config/axiosInstance";
import "./Dashboard.css";
import { useNavigate } from "react-router-dom";
import {
  Plus,
  X,
  Video,
  Users,
  Clock,
  Calendar,
  Copy,
  Play,
  UserCheck,
  Settings,
  LogOut,
  Bell,
  Search,
  Filter,
  MoreVertical,
  ExternalLink,
  AlertTriangle,
  ClipboardClock,
} from "lucide-react";

const Dashboard = () => {
  const [meetings, setMeetings] = useState([]);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    roomName: "",
    ownerName: "",
    description: "",
    scheduledTime: "",
    validityDuration: 60,
  });

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

  const fetchMeetings = async () => {
    try {
      const response = await axios.get("/meetings");
      setMeetings(response.data.data || []);
    } catch (error) {
      console.error("Error fetching meetings:", error);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleCreateMeeting = async (e) => {
    e.preventDefault();

    if (!formData.roomName || !formData.ownerName || !formData.scheduledTime) {
      return;
    }

    setLoading(true);

    try {
      const response = await axios.post("/meetings", formData);
      setMeetings((prev) => [response.data.data, ...prev]);
      setFormData({
        roomName: "",
        ownerName: "",
        description: "",
        scheduledTime: "",
        validityDuration: 60,
      });
      setShowCreateForm(false);
    } catch (error) {
      console.error("Error creating meeting:", error);
    } finally {
      setLoading(false);
    }
  };

  const copyOwnerLink = (meeting) => {
    navigator.clipboard.writeText(meeting.ownerMeetingUrl);
  };

  const copyParticipantLink = (meeting) => {
    navigator.clipboard.writeText(meeting.participantMeetingUrl);
  };

  const navigateToMeeting = (meeting, role) => {
    if (isExpired(meeting)) {
      return;
    }
    const token =
      role === "moderator" ? meeting.moderatorToken : meeting.participantToken;

    if (!token) {
      return;
    }

    sessionStorage.setItem("meetingToken", token);
    sessionStorage.setItem("meetingRole", role);
    sessionStorage.setItem("meetingId", meeting._id);

    const params = new URLSearchParams({
      room: meeting.roomId,
      role: role,
      ...(role === "moderator" && { name: meeting.ownerName }),
    });

    navigate(`/meeting?${params.toString()}`);
  };

  const startMeetingAsOwner = (meeting) => {
    navigateToMeeting(meeting, "moderator");
  };

  const joinAsParticipant = (meeting) => {
    navigateToMeeting(meeting, "participant");
  };

  const isExpired = (meeting) => {
    return new Date() > new Date(meeting.expiryTime);
  };

  const formatDuration = (minutes) => {
    if (minutes < 60) return `${minutes} min`;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
  };

  const getStatusColor = (meeting) => {
    if (isExpired(meeting)) return "expired";
    return meeting.status || "scheduled";
  };

  const filteredMeetings = meetings.filter((meeting) => {
    const matchesSearch =
      meeting.roomName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      meeting.ownerName.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesFilter =
      filterStatus === "all" ||
      (filterStatus === "expired" && isExpired(meeting)) ||
      (filterStatus === "active" && !isExpired(meeting));

    return matchesSearch && matchesFilter;
  });

  const handleLogout = () => {
    localStorage.removeItem("token");
    navigate("/");
  };

  return (
    <div className="dashboard-container">
      {/* Header */}
      <div className="dashboard-header">
        <div className="header-left">
          <div className="brand-section">
            <Video className="brand-icon" size={32} />
            <div className="brand-text">
              <h1>Meeting Hub</h1>
              <p>Admin Dashboard</p>
            </div>
          </div>
        </div>

        <div className="header-right">
          <div className="header-actions">
            <button className="icon-button notification-btn">
              <Bell size={20} />
              <span className="notification-dot"></span>
            </button>

            <button className="icon-button settings-btn">
              <Settings size={20} />
            </button>

            <button
              className="btn-primary create-btn"
              onClick={() => setShowCreateForm(!showCreateForm)}
            >
              {showCreateForm ? (
                <>
                  <X size={20} />
                  Cancel
                </>
              ) : (
                <>
                  <Plus size={20} />
                  Create Meeting
                </>
              )}
            </button>

            <button className="logout-btn" onClick={handleLogout}>
              <LogOut size={20} />
            </button>
          </div>
        </div>
      </div>

      {/* Create Meeting Form */}
      {showCreateForm && (
        <div className="create-form-overlay">
          <div className="create-form">
            <div className="form-header">
              <div className="form-title">
                <Video size={24} />
                <h2>Create New Meeting</h2>
              </div>
              <button
                className="close-btn"
                onClick={() => setShowCreateForm(false)}
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleCreateMeeting}>
              <div className="form-grid">
                <div className="form-group">
                  <label>Meeting Name *</label>
                  <input
                    type="text"
                    name="roomName"
                    value={formData.roomName}
                    onChange={handleInputChange}
                    placeholder="Enter meeting name"
                    required
                  />
                </div>

                <div className="form-group">
                  <label>Host Name *</label>
                  <input
                    type="text"
                    name="ownerName"
                    value={formData.ownerName}
                    onChange={handleInputChange}
                    placeholder="Enter host name"
                    required
                  />
                </div>

                <div className="form-group full-width">
                  <label>Description (Optional)</label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={handleInputChange}
                    placeholder="Meeting description"
                    rows={3}
                  />
                </div>

                <div className="form-group">
                  <label>Scheduled Time *</label>
                  <input
                    type="datetime-local"
                    name="scheduledTime"
                    value={formData.scheduledTime}
                    onChange={handleInputChange}
                    required
                  />
                </div>

                <div className="form-group">
                  <label>Duration *</label>
                  <select
                    name="validityDuration"
                    value={formData.validityDuration}
                    onChange={handleInputChange}
                    required
                  >
                    <option value={30}>30 minutes</option>
                    <option value={60}>1 hour</option>
                    <option value={120}>2 hours</option>
                    <option value={240}>4 hours</option>
                    <option value={480}>8 hours</option>
                    <option value={1440}>24 hours</option>
                  </select>
                </div>
              </div>

              <div className="form-actions">
                <button
                  type="button"
                  className="btn-secondary"
                  onClick={() => setShowCreateForm(false)}
                >
                  Cancel
                </button>
                <button type="submit" disabled={loading} className="btn-create">
                  {loading ? (
                    <>
                      <div className="spinner"></div>
                      Creating...
                    </>
                  ) : (
                    <>
                      <Plus size={20} />
                      Create Meeting
                    </>
                  )}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Search and Filter Section */}
      <div className="controls-section">
        <div className="search-filter-bar">
          <div className="search-group">
            <Search className="search-icon" size={20} />
            <input
              type="text"
              placeholder="Search meetings..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="search-input"
            />
          </div>

          <div className="filter-group">
            <Filter size={20} />
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="filter-select"
            >
              <option value="all">All Meetings</option>
              <option value="active">Active</option>
              <option value="expired">Expired</option>
            </select>
          </div>
        </div>

        <div className="stats-overview">
          <div className="stat-card">
            <div className="stat-icon total">
              <Video size={24} />
            </div>
            <div className="stat-info">
              <h3>{meetings.length}</h3>
              <p>Total Meetings</p>
            </div>
          </div>

          <div className="stat-card">
            <div className="stat-icon active">
              <Play size={24} />
            </div>
            <div className="stat-info">
              <h3>{meetings.filter((m) => !isExpired(m)).length}</h3>
              <p>Active</p>
            </div>
          </div>

          <div className="stat-card">
            <div className="stat-icon expired">
              <Clock size={24} />
            </div>
            <div className="stat-info">
              <h3>{meetings.filter((m) => isExpired(m)).length}</h3>
              <p>Expired</p>
            </div>
          </div>
        </div>
      </div>

      {/* Meetings Grid */}
      <div className="meetings-section">
        <div className="recent-meetings-header">
          <ClipboardClock />
          <h2>Recent Meetings ({meetings.length})</h2>
        </div>

        {filteredMeetings.length === 0 ? (
          <div className="no-meetings">
            <p>No meetings created yet. Create your first meeting!</p>
          </div>
        ) : (
          <div className="meetings-grid">
            {filteredMeetings.map((meeting) => (
              <div
                key={meeting._id}
                className={`meeting-card ${
                  isExpired(meeting) ? "expired" : ""
                }`}
              >
                <div className="meeting-header">
                  <h3>🎯 {meeting.roomName}</h3>
                  <span
                    className={`status ${
                      isExpired(meeting) ? "expired" : meeting.status
                    }`}
                  >
                    {isExpired(meeting) ? "⏰ Expired" : `📊 ${meeting.status}`}
                  </span>
                </div>

                <div className="meeting-details">
                  <p>
                    <strong>👤 Host:</strong> {meeting.ownerName}
                  </p>
                  <p>
                    <strong>🏷️ Room ID:</strong> <code>{meeting.roomId}</code>
                  </p>
                  {meeting.description && (
                    <p>
                      <strong>📝 Description:</strong> {meeting.description}
                    </p>
                  )}
                  <p>
                    <strong>📅 Scheduled:</strong>{" "}
                    {new Date(meeting.scheduledTime).toLocaleString()}
                  </p>
                  <p>
                    <strong>⏱️ Duration:</strong>{" "}
                    {formatDuration(meeting.validityDuration)}
                  </p>
                  <p>
                    <strong>⏰ Expires:</strong>{" "}
                    {new Date(meeting.expiryTime).toLocaleString()}
                  </p>
                </div>

                <div className="meeting-actions">
                  {!isExpired(meeting) ? (
                    <>
                      <button
                        onClick={() => startMeetingAsOwner(meeting)}
                        className="btn-owner"
                        title="Start with moderator privileges"
                      >
                        🚀 Start as Host
                      </button>

                      <button
                        onClick={() => joinAsParticipant(meeting)}
                        className="btn-participant"
                        title="Join as participant"
                      >
                        👥 Join as Guest
                      </button>

                      <button
                        onClick={() => copyOwnerLink(meeting)}
                        className="btn-copy-owner"
                        title="Copy host/moderator link"
                      >
                        📋 Copy Host Link
                      </button>

                      <button
                        onClick={() => copyParticipantLink(meeting)}
                        className="btn-copy-participant"
                        title="Copy participant link"
                      >
                        📋 Copy Guest Link
                      </button>
                    </>
                  ) : (
                    <span className="expired-text">⏰ Meeting has expired</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;
