import React, { useState, useEffect } from 'react';
import type { ComponentConfig } from '@measured/puck';
import type { BusinessHoursProps } from '../../types';
import { Clock, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import api from '../../../api/client';

interface DayHours {
  day: string;
  is_open: boolean;
  open: string | null;
  close: string | null;
}

const formatTime = (time: string | null): string => {
  if (!time) return '';
  try {
    const [hour, min] = time.split(':').map(Number);
    if (isNaN(hour) || isNaN(min)) return time;
    const period = hour >= 12 ? 'PM' : 'AM';
    const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
    return `${displayHour}:${min.toString().padStart(2, '0')} ${period}`;
  } catch {
    return time;
  }
};

const DEFAULT_HOURS: DayHours[] = [
  { day: 'Monday', is_open: true, open: '09:00', close: '17:00' },
  { day: 'Tuesday', is_open: true, open: '09:00', close: '17:00' },
  { day: 'Wednesday', is_open: true, open: '09:00', close: '17:00' },
  { day: 'Thursday', is_open: true, open: '09:00', close: '17:00' },
  { day: 'Friday', is_open: true, open: '09:00', close: '17:00' },
  { day: 'Saturday', is_open: false, open: null, close: null },
  { day: 'Sunday', is_open: false, open: null, close: null },
];

export const BusinessHours: ComponentConfig<BusinessHoursProps> = {
  label: 'Business Hours',
  fields: {
    showCurrent: {
      type: 'radio',
      label: 'Highlight Current Day',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    title: {
      type: 'text',
      label: 'Title',
    },
  },
  defaultProps: {
    showCurrent: true,
    title: 'Business Hours',
  },
  render: ({ showCurrent, title }) => {
    const [hours, setHours] = useState<DayHours[]>(DEFAULT_HOURS);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const today = new Date().toLocaleDateString('en-US', { weekday: 'long' });

    useEffect(() => {
      const fetchHours = async () => {
        try {
          setIsLoading(true);
          const response = await api.get('/public/weekly-hours/');
          if (response.data?.hours) {
            setHours(response.data.hours);
          }
          setError(null);
        } catch (err: any) {
          console.error('Failed to fetch business hours:', err);
          // Use defaults on error
          setError(null);
        } finally {
          setIsLoading(false);
        }
      };

      fetchHours();
    }, []);

    if (isLoading) {
      return (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
          {title && (
            <div className="flex items-center gap-3 mb-6">
              <Clock className="w-6 h-6 text-indigo-600 dark:text-indigo-400" />
              <h3 className="text-xl font-semibold text-gray-900 dark:text-white">
                {title}
              </h3>
            </div>
          )}
          <div className="flex items-center justify-center py-8">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        </div>
      );
    }

    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        {title && (
          <div className="flex items-center gap-3 mb-6">
            <Clock className="w-6 h-6 text-indigo-600 dark:text-indigo-400" />
            <h3 className="text-xl font-semibold text-gray-900 dark:text-white">
              {title}
            </h3>
          </div>
        )}

        <div className="space-y-3">
          {hours.map(({ day, is_open, open, close }) => {
            const isToday = showCurrent && day === today;

            return (
              <div
                key={day}
                className={`flex items-center justify-between py-2 px-3 rounded-lg ${
                  isToday
                    ? 'bg-indigo-50 dark:bg-indigo-900/20'
                    : ''
                }`}
              >
                <div className="flex items-center gap-2">
                  {is_open ? (
                    <CheckCircle className="w-4 h-4 text-green-500" />
                  ) : (
                    <XCircle className="w-4 h-4 text-red-400" />
                  )}
                  <span
                    className={`font-medium ${
                      isToday
                        ? 'text-indigo-600 dark:text-indigo-400'
                        : 'text-gray-700 dark:text-gray-300'
                    }`}
                  >
                    {day}
                    {isToday && (
                      <span className="ml-2 text-xs bg-indigo-600 text-white px-2 py-0.5 rounded-full">
                        Today
                      </span>
                    )}
                  </span>
                </div>
                <span
                  className={`${
                    is_open
                      ? 'text-gray-600 dark:text-gray-400'
                      : 'text-red-500 dark:text-red-400'
                  }`}
                >
                  {is_open && open && close
                    ? `${formatTime(open)} - ${formatTime(close)}`
                    : 'Closed'}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    );
  },
};

export default BusinessHours;
