import { Card, Row, Col } from 'react-bootstrap';

type ServiceItem = {
  id: number;
  service_id: number;
  name: string;
  slug: string;
  color?: string | null;
  rotation_days?: number | null;
  last_service?: string | null;
  next_service?: string | null;
  force_current?: boolean;
};

type Props = {
  services?: ServiceItem[];
};

const formatDate = (value?: string | null) => {
  if (!value) return '—';

  const d = new Date(`${value}T00:00:00`);
  if (Number.isNaN(d.getTime())) return value;

  return d.toLocaleDateString('en-CA', {
    month: 'short',
    day: '2-digit',
    year: 'numeric',
  });
};

const rotationLabel = (days?: number | null) => {
  if (!days || days <= 0) return 'No schedule';

  if (days % 365 === 0) {
    const years = days / 365;
    return years === 1 ? 'Annual' : `${years} Years`;
  }

  if (days % 30 === 0) {
    const months = days / 30;
    return months === 1 ? '1 Month' : `${months} Months`;
  }

  if (days % 7 === 0) {
    const weeks = days / 7;
    return weeks === 1 ? '1 Week' : `${weeks} Weeks`;
  }

  return `${days} Days`;
};

const serviceStatus = (nextService?: string | null) => {
  if (!nextService) {
    return {
      tone: 'muted',
      color: '#6c757d',
      label: 'No schedule',
    };
  }

  const today = new Date();
  const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate());

  const due = new Date(`${nextService}T00:00:00`);
  if (Number.isNaN(due.getTime())) {
    return {
      tone: 'muted',
      color: '#6c757d',
      label: 'No schedule',
    };
  }

  const msPerDay = 1000 * 60 * 60 * 24;
  const diffDays = Math.round((due.getTime() - todayOnly.getTime()) / msPerDay);

  if (diffDays < -30) {
    return {
      tone: 'danger',
      color: '#dc3545',
      label: `Past Due: ${Math.abs(diffDays)} day${Math.abs(diffDays) === 1 ? '' : 's'}`,
    };
  }

  if (diffDays <= 30) {
    if (diffDays < 0) {
      return {
        tone: 'warning',
        color: '#fd7e14',
        label: `Past Due: ${Math.abs(diffDays)} day${Math.abs(diffDays) === 1 ? '' : 's'}`,
      };
    }

    if (diffDays === 0) {
      return {
        tone: 'warning',
        color: '#fd7e14',
        label: 'Due today',
      };
    }

    return {
      tone: 'warning',
      color: '#fd7e14',
      label: `Due in ${diffDays} day${diffDays === 1 ? '' : 's'}`,
    };
  }

  return {
    tone: 'success',
    color: '#198754',
    label: 'Current',
  };
};

export default function ServicesCard({ services = [] }: Props) {
  return (
    <Card className="gd-module-card mb-4">
      <Card.Body>
        <h5 className="mb-4">Services</h5>

        {services.length ? (
          <Row className="g-4">
            {services.map((service) => {
              const status = serviceStatus(service.next_service);

              return (
                <Col md={6} xl={4} key={service.id}>
                  <div className="h-100">
                    <div className="d-flex align-items-center gap-2 mb-2">
                      <span
                        title={service.name}
                        style={{
                          width: 10,
                          height: 10,
                          minWidth: 10,
                          minHeight: 10,
                          flex: '0 0 10px',
                          borderRadius: '50%',
                          display: 'inline-block',
                          backgroundColor: service.color || '#6c757d',
                        }}
                      />
                      <strong>{service.name}</strong>
                    </div>

                    <div className="small">
                      <div className="mb-1">
                        Rotation:{' '}
                        <span className="text-muted">{rotationLabel(service.rotation_days)}</span>
                      </div>

                      <div className="mb-1">
                        Next Service:{' '}
                        <span className="text-muted">{formatDate(service.next_service)}</span>
                      </div>

                      <div className="mb-1">
                        <span style={{ color: status.color, fontWeight: 600 }}>
                          {status.label}
                        </span>
                      </div>

                      <div>
                        Last Service:{' '}
                        <span className="text-muted">{formatDate(service.last_service)}</span>
                      </div>
                    </div>
                  </div>
                </Col>
              );
            })}
          </Row>
        ) : (
          <div className="text-muted">No services assigned</div>
        )}
      </Card.Body>
    </Card>
  );
}