import { Button } from "@xtablo/ui/components/button";
import { Card, CardAction, CardContent, CardHeader, CardTitle } from "@xtablo/ui/components/card";
import { Switch } from "@xtablo/ui/components/switch";
import { TimeInput } from "@xtablo/ui/components/time-input";
import { Copy as CopyIcon, Minus as MinusIcon, Plus as PlusIcon } from "lucide-react";

interface TimeRange {
  start: string;
  end: string;
}

interface AvailabilityCardProps {
  day: number;
  enabled: boolean;
  onEnabledChange: (enabled: boolean) => void;
  timeRanges: TimeRange[];
  onTimeRangesChange: (ranges: TimeRange[]) => void;
  onCopyToOtherDays?: (sourceDay: number, enabled: boolean, timeRanges: TimeRange[]) => void;
}

const MAX_END_TIME_MINUTES = 23 * 60 + 30; // 23:30

const DAYS_OF_WEEK_DISPLAY = [
  "Lundi",
  "Mardi",
  "Mercredi",
  "Jeudi",
  "Vendredi",
  "Samedi",
  "Dimanche",
];

function timeToMinutes(time: string): number {
  const [hours, minutes] = time.split(":").map(Number);
  return hours * 60 + minutes;
}

function minutesToTime(minutes: number): string {
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return `${hours.toString().padStart(2, "0")}:${mins.toString().padStart(2, "0")}`;
}

export function AvailabilityCard({
  day,
  enabled,
  onEnabledChange,
  timeRanges,
  onTimeRangesChange,
  onCopyToOtherDays,
}: AvailabilityCardProps) {
  const dayDisplay = DAYS_OF_WEEK_DISPLAY[day];

  const handleAddRange = () => {
    // Find a free slot for the new range
    const sortedRanges = [...timeRanges].sort(
      (a, b) => timeToMinutes(a.start) - timeToMinutes(b.start)
    );
    let newStart = "09:00";
    let newEnd = "17:00";

    // If no existing ranges, ensure default doesn't exceed 23:30
    if (sortedRanges.length === 0) {
      newEnd = "17:00"; // Safe default
    }

    for (let i = 0; i < sortedRanges.length; i++) {
      const currentRange = sortedRanges[i];
      const nextRange = sortedRanges[i + 1];

      if (!nextRange) {
        // If this is the last range, add new range after it
        const currentEnd = timeToMinutes(currentRange.end);
        if (currentEnd + 120 <= MAX_END_TIME_MINUTES) {
          // At least 2 hours before 23:30
          newStart = minutesToTime(currentEnd + 30);
          newEnd = minutesToTime(Math.min(currentEnd + 240, MAX_END_TIME_MINUTES)); // 4 hours or 23:30
        }
        break;
      }

      const gap = timeToMinutes(nextRange.start) - timeToMinutes(currentRange.end);
      if (gap >= 120) {
        // At least 2 hours gap
        newStart = minutesToTime(timeToMinutes(currentRange.end) + 30);
        newEnd = minutesToTime(Math.min(timeToMinutes(nextRange.start) - 30, MAX_END_TIME_MINUTES));
        break;
      }
    }

    const newRanges = [...timeRanges, { start: newStart, end: newEnd }];
    onTimeRangesChange(newRanges);
  };

  const handleDeleteRange = (index: number) => {
    const newRanges = timeRanges.filter((_, i) => i !== index);
    onTimeRangesChange(newRanges);
  };

  const validateTimeRange = (ranges: TimeRange[], index: number): boolean => {
    const currentRange = ranges[index];
    const currentStart = timeToMinutes(currentRange.start);
    const currentEnd = timeToMinutes(currentRange.end);

    // Ensure end time is after start time
    if (currentEnd <= currentStart) {
      return false;
    }

    // Check for overlaps with other ranges
    for (let i = 0; i < ranges.length; i++) {
      if (i === index) continue;
      const range = ranges[i];
      const start = timeToMinutes(range.start);
      const end = timeToMinutes(range.end);

      if (
        (currentStart >= start && currentStart < end) ||
        (currentEnd > start && currentEnd <= end) ||
        (currentStart <= start && currentEnd >= end)
      ) {
        return false;
      }
    }

    return true;
  };

  return (
    <Card className="w-full bg-muted/30">
      <CardHeader>
        <CardTitle className="text-lg">{dayDisplay}</CardTitle>
        {onCopyToOtherDays && enabled && timeRanges.length > 0 && (
          <CardAction>
            <Button
              size="sm"
              variant="outline"
              onClick={() => onCopyToOtherDays(day, enabled, timeRanges)}
              className="h-6 px-2 text-xs"
            >
              <CopyIcon className="size-3 mr-1" />
              Copier
            </Button>
          </CardAction>
        )}
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="flex items-center gap-2">
          <Switch checked={enabled} onCheckedChange={onEnabledChange} />
          <label
            className={`font-medium text-sm ${
              enabled ? "text-foreground" : "text-muted-foreground"
            }`}
          >
            {enabled ? "Disponible" : "Indisponible"}
          </label>
        </div>

        {/* Time Ranges */}
        <div className="space-y-2">
          {timeRanges.map((range, index) => (
            <div key={index} className="flex items-center gap-2">
              <TimeInput
                value={range.start}
                onChange={(value) => {
                  const newRanges = [...timeRanges];
                  newRanges[index] = {
                    ...range,
                    start: value,
                  };
                  if (validateTimeRange(newRanges, index)) {
                    onTimeRangesChange(newRanges);
                  }
                }}
                isDisabled={!enabled}
                className="h-8 text-sm max-w-32"
                id={`start-${day}-${index}`}
              />
              <span className="text-muted-foreground text-sm">-</span>
              <TimeInput
                value={range.end}
                onChange={(value) => {
                  const newRanges = [...timeRanges];
                  newRanges[index] = {
                    ...range,
                    end: value,
                  };
                  if (validateTimeRange(newRanges, index)) {
                    onTimeRangesChange(newRanges);
                  }
                }}
                isDisabled={!enabled}
                className="h-8 text-sm max-w-32"
                id={`end-${day}-${index}`}
              />
              {timeRanges.length > 1 && (
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteRange(index);
                  }}
                  disabled={!enabled}
                  variant="outline"
                  size="icon"
                  className="hover:text-red-500 hover:bg-red-50/10 dark:hover:bg-red-950/10"
                >
                  <MinusIcon />
                </Button>
              )}
            </div>
          ))}
          {timeRanges.length < 3 && (
            <Button
              onClick={() => handleAddRange()}
              disabled={!enabled}
              variant="outline"
              size="sm"
              className="h-8 px-3 flex items-center text-sm"
            >
              <PlusIcon className="size-4 mr-1" />
              Ajouter une plage horaire
            </Button>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
