import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Calendar } from '@/components/ui/calendar';
import { cn } from '@/lib/utils';
import { Calendar as CalendarIcon, ChevronDown, Clock, Link2, MapPin, Repeat, Tag, UserPlus, Users, X } from 'lucide-react';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Textarea } from '@/components/ui/textarea';
import { format } from 'date-fns';
import * as React from 'react';

interface EventTabProps {
    // Date & Time
    date: string;
    setDate: (value: string) => void;
    startTime: string;
    setStartTime: (value: string) => void;
    endTime: string;
    setEndTime: (value: string) => void;
    isAllDay: boolean;
    setIsAllDay: (value: boolean) => void;

    // Event specific
    meetingType: string;
    setMeetingType: (value: string) => void;
    meetingStatus: string;
    setMeetingStatus: (value: string) => void;
    location: string;
    setLocation: (value: string) => void;
    meetingLink: string;
    setMeetingLink: (value: string) => void;

    // Recurrence
    recurrence: string;
    showRecurrenceConfig: boolean;
    setShowRecurrenceConfig: (value: boolean) => void;
    recurrenceDisplayText: string;
    recurrenceOptions: any[];
    handleRecurrenceChange: (value: string) => void;

    // Participants
    selectedParticipants: string[];
    users: any[];
    showParticipantPicker: boolean;
    setShowParticipantPicker: (value: boolean) => void;
    addParticipant: (userId: string) => void;
    removeParticipant: (userId: string) => void;
    getUserDetails: (userId: string) => any;

    // Advanced
    showAdvanced: boolean;
    setShowAdvanced: (value: boolean) => void;
    description: string;
    setDescription: (value: string) => void;
    isEditMode: boolean;

    // Helpers
    handleStartTimeChange: (value: string) => void;
    formatDuration: () => string;

    // Constants
    EVENT_TYPES: any[];
    EVENT_STATUSES: any[];
}

export function EventTab({
    date, setDate, startTime, setStartTime, endTime, setEndTime,
    isAllDay, setIsAllDay, meetingType, setMeetingType, meetingStatus, setMeetingStatus,
    location, setLocation, meetingLink, setMeetingLink,
    recurrence, showRecurrenceConfig, setShowRecurrenceConfig, recurrenceDisplayText,
    recurrenceOptions, handleRecurrenceChange,
    selectedParticipants, users, showParticipantPicker, setShowParticipantPicker,
    addParticipant, removeParticipant, getUserDetails,
    showAdvanced, setShowAdvanced, description, setDescription, isEditMode,
    handleStartTimeChange, formatDuration,
    EVENT_TYPES, EVENT_STATUSES
}: EventTabProps) {
    const currentModule = {
        textColor: 'text-violet-600',
        bgLight: 'bg-violet-50',
        borderColor: 'border-violet-200',
    };

    const [showDatePicker, setShowDatePicker] = React.useState(false);
    const dateValue = date ? new Date(date) : undefined;

    return (
        <div className="space-y-3">
            {/* Date & Time Section */}
            <div className="rounded-lg border border-slate-200 p-4">
                {/* All Day Toggle */}
                <div className="mb-4 flex items-center justify-between">
                    <Label className="font-medium text-slate-700">Date & Time</Label>
                    <label className="flex cursor-pointer items-center gap-2">
                        <Checkbox
                            id="all-day"
                            checked={isAllDay}
                            onCheckedChange={(checked) => setIsAllDay(checked as boolean)}
                        />
                        <span className="text-sm text-slate-600">All day</span>
                    </label>
                </div>

                {/* Date */}
                <div className="mb-3">
                    <Popover open={showDatePicker} onOpenChange={setShowDatePicker}>
                        <PopoverTrigger asChild>
                            <Button
                                variant="outline"
                                className={cn(
                                    'h-10 w-full justify-start text-left font-normal',
                                    !dateValue && 'text-muted-foreground'
                                )}
                            >
                                <CalendarIcon className="mr-2 h-4 w-4 shrink-0" />
                                <span className="truncate">
                                    {dateValue ? format(dateValue, 'MM/dd/yyyy') : 'Pick a date'}
                                </span>
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                            <Calendar
                                mode="single"
                                selected={dateValue}
                                onSelect={(selectedDate) => {
                                    if (selectedDate) {
                                        setDate(format(selectedDate, 'yyyy-MM-dd'));
                                    } else {
                                        setDate('');
                                    }
                                    setShowDatePicker(false);
                                }}
                                disabled={(date) => date < new Date(new Date().setHours(0, 0, 0, 0))}
                                initialFocus
                            />
                        </PopoverContent>
                    </Popover>
                </div>

                {/* Time Range */}
                {!isAllDay && (
                    <div className="flex items-center gap-2">
                        <div className="relative flex-1">
                            <Clock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                            <Input
                                type="time"
                                value={startTime}
                                onChange={(e) => handleStartTimeChange(e.target.value)}
                                className="h-10 border-slate-200 pl-10"
                            />
                        </div>
                        <span className="text-slate-400">-</span>
                        <div className="flex-1">
                            <Input
                                type="time"
                                value={endTime}
                                onChange={(e) => setEndTime(e.target.value)}
                                className="h-10 border-slate-200"
                            />
                        </div>
                        <Badge variant="outline" className="ml-2 whitespace-nowrap text-slate-600">
                            {formatDuration()}
                        </Badge>
                    </div>
                )}
            </div>

            {/* Recurrence */}
            <Popover open={showRecurrenceConfig} onOpenChange={setShowRecurrenceConfig}>
                <PopoverTrigger asChild>
                    <Button
                        variant="outline"
                        className="w-full justify-between border-slate-200"
                    >
                        <span className="flex items-center gap-2">
                            <Repeat className="h-4 w-4 text-slate-400" />
                            {recurrenceDisplayText}
                        </span>
                        <ChevronDown className="h-4 w-4 text-slate-400" />
                    </Button>
                </PopoverTrigger>
                <PopoverContent className="w-64 p-1" align="start">
                    {recurrenceOptions.map((opt) => (
                        <button
                            key={opt.value}
                            onClick={() => handleRecurrenceChange(opt.value)}
                            className={cn(
                                'w-full rounded-md px-3 py-2 text-left text-sm transition-colors',
                                recurrence === opt.value
                                    ? 'bg-slate-100 text-slate-900 font-medium'
                                    : 'text-slate-600 hover:bg-slate-50',
                            )}
                        >
                            {opt.label}
                        </button>
                    ))}
                </PopoverContent>
            </Popover>

            {/* Event Type */}
            <Select value={meetingType} onValueChange={setMeetingType}>
                <SelectTrigger className="border-slate-200">
                    <SelectValue />
                </SelectTrigger>
                <SelectContent>
                    {EVENT_TYPES.map((type) => (
                        <SelectItem key={type.value} value={type.value}>
                            <div className="flex items-center gap-2">
                                <div className={cn('h-2 w-2 rounded-full', type.color)} />
                                {type.label}
                            </div>
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>

            {/* Advanced Fields - Always shown for now, can be toggled */}
            {showAdvanced && (
                <div className="space-y-4 rounded-lg border border-slate-200 bg-slate-50 p-4">
                    {/* Participants */}
                    <div>
                        <Label className="mb-3 block text-sm font-medium text-slate-700">Participants</Label>
                        <div className="mb-3 flex flex-wrap gap-2">
                            {selectedParticipants.map((userId) => {
                                const user = getUserDetails(userId);
                                return (
                                    <Badge
                                        key={userId}
                                        variant="secondary"
                                        className="flex items-center gap-2 rounded-full border border-slate-200 bg-white py-1.5 pr-2 pl-1.5"
                                    >
                                        <Avatar className="h-6 w-6">
                                            <AvatarFallback className={cn('text-xs', currentModule.bgLight, currentModule.textColor)}>
                                                {user?.label?.charAt(0).toUpperCase() || 'U'}
                                            </AvatarFallback>
                                        </Avatar>
                                        <span className="text-sm font-medium text-slate-700">{user?.label || 'Unknown'}</span>
                                        <button
                                            onClick={() => removeParticipant(userId)}
                                            className="ml-1 rounded-full p-0.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600"
                                        >
                                            <X className="h-3 w-3" />
                                        </button>
                                    </Badge>
                                );
                            })}
                        </div>
                        <Popover open={showParticipantPicker} onOpenChange={setShowParticipantPicker}>
                            <PopoverTrigger asChild>
                                <Button variant="outline" size="sm" className="h-9 gap-2 border-dashed border-slate-300">
                                    <UserPlus className="h-4 w-4" />
                                    Add participant
                                </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-64 p-1" align="start">
                                <div className="max-h-48 overflow-y-auto">
                                    {users
                                        .filter((u) => !selectedParticipants.includes(u.value))
                                        .map((user) => (
                                            <button
                                                key={user.value}
                                                onClick={() => addParticipant(user.value)}
                                                className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-slate-50"
                                            >
                                                <Avatar className="h-8 w-8">
                                                    <AvatarFallback className="bg-violet-100 text-sm text-violet-600">
                                                        {user.label.charAt(0).toUpperCase()}
                                                    </AvatarFallback>
                                                </Avatar>
                                                <span className="font-medium">{user.label}</span>
                                            </button>
                                        ))}
                                    {users.filter((u) => !selectedParticipants.includes(u.value)).length === 0 && (
                                        <p className="py-4 text-center text-sm text-slate-400">No more users available</p>
                                    )}
                                </div>
                            </PopoverContent>
                        </Popover>
                    </div>

                    {/* Meeting Link */}
                    <div>
                        <Label htmlFor="meeting-link" className="mb-3 block text-sm font-medium text-slate-700">Meeting Link</Label>
                        <div className="relative">
                            <Link2 className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                            <Input
                                id="meeting-link"
                                value={meetingLink}
                                onChange={(e) => setMeetingLink(e.target.value)}
                                placeholder="https://meet.google.com/..."
                                className="h-10 border-slate-200 pl-10"
                            />
                        </div>
                    </div>

                    {/* Location */}
                    <div>
                        <Label htmlFor="location" className="mb-3 block text-sm font-medium text-slate-700">Location</Label>
                        <div className="relative">
                            <MapPin className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                            <Input
                                id="location"
                                value={location}
                                onChange={(e) => setLocation(e.target.value)}
                                placeholder="Add location"
                                className="h-10 border-slate-200 pl-10"
                            />
                        </div>
                    </div>

                    {/* Description */}
                    <div>
                        <Label htmlFor="description" className="mb-3 block text-sm font-medium text-slate-700">Description</Label>
                        <Textarea
                            id="description"
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            placeholder="Add description..."
                            className="min-h-[100px] resize-none border-slate-200"
                        />
                    </div>

                    {/* Status - for Event in edit mode */}
                    {isEditMode && (
                        <div>
                            <Label className="mb-3 block text-sm font-medium text-slate-700">Status</Label>
                            <div className="flex flex-wrap gap-2">
                                {EVENT_STATUSES.map((status) => (
                                    <button
                                        key={status.value}
                                        onClick={() => setMeetingStatus(status.value)}
                                        className={cn(
                                            'rounded-full px-3 py-1.5 text-xs font-medium transition-all',
                                            meetingStatus === status.value
                                                ? status.lightColor
                                                : 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-50',
                                        )}
                                    >
                                        {status.label}
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}
