import { useState, useEffect } from 'react';
import { Calendar as CalendarIcon, Users, Wifi, Copy, CheckCheck } from 'lucide-react';
import { calendarAPI } from '../services/api';
import { useConfig } from '../contexts/ConfigContext';


function CopyButton({ text }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };
  return (
    <button onClick={copy} className="ml-2 text-gray-400 hover:text-gray-600" title="Copy">
      {copied ? <CheckCheck className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
    </button>
  );
}

function InfoRow({ label, value }) {
  return (
    <div className="flex items-center justify-between py-1.5 border-b border-gray-100 last:border-0">
      <span className="text-sm text-gray-500 w-32 shrink-0">{label}</span>
      <div className="flex items-center">
        <span className="text-sm font-mono font-medium text-gray-800">{value}</span>
        <CopyButton text={value} />
      </div>
    </div>
  );
}

function Calendar() {
  const { domain = 'cell', service_ips = {}, service_configs = {} } = useConfig();
  const cellHost    = `calendar.${domain}`;
  const calendarIp  = service_ips.vip_calendar || '172.20.0.21';
  const dnsIp       = service_ips.dns           || '172.20.0.3';
  const calendarPort = service_configs.calendar?.port ?? 5232;
  const [users, setUsers] = useState([]);
  const [status, setStatus] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

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

  const fetchCalendarData = async () => {
    try {
      const [usersResponse, statusResponse] = await Promise.all([
        calendarAPI.getUsers(),
        calendarAPI.getStatus()
      ]);
      setUsers(usersResponse.data);
      setStatus(statusResponse.data);
    } catch (error) {
      console.error('Failed to fetch calendar data:', error);
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">Calendar &amp; Contacts</h1>
        <p className="mt-2 text-gray-600">Radicale CalDAV / CardDAV server</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Connection Info */}
        <div className="card">
          <div className="flex items-center mb-4">
            <Wifi className="h-5 w-5 text-primary-500 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Connect your device</h3>
          </div>
          <p className="text-xs text-gray-500 mb-3">
            Use these settings in your calendar / contacts app (iOS, Android, Thunderbird, etc.)
          </p>
          <div className="bg-gray-50 rounded-lg px-4 py-2">
            <InfoRow label="Server URL"    value={`http://${cellHost}`} />
            <InfoRow label="CalDAV path"   value={`http://${cellHost}/`} />
            <InfoRow label="CardDAV path"  value={`http://${cellHost}/`} />
            <InfoRow label="Port"          value="80" />
            <InfoRow label="Direct IP"     value={calendarIp} />
            <InfoRow label="Direct port"   value={String(calendarPort)} />
            <InfoRow label="Protocol"      value="HTTP (CalDAV/CardDAV)" />
          </div>
          <p className="text-xs text-gray-400 mt-3">
            Requires VPN connection. DNS server must be set to <span className="font-mono">{dnsIp}</span>.
          </p>
        </div>

        {/* iOS / Android quick guide */}
        <div className="card">
          <div className="flex items-center mb-4">
            <CalendarIcon className="h-5 w-5 text-primary-500 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Quick setup guide</h3>
          </div>
          <div className="space-y-3 text-sm text-gray-700">
            <div>
              <p className="font-medium text-gray-900 mb-1">iOS (Settings → Calendar → Accounts)</p>
              <ol className="list-decimal ml-4 space-y-0.5 text-xs text-gray-600">
                <li>Add Account → Other → Add CalDAV Account</li>
                <li>Server: <span className="font-mono">{cellHost}</span></li>
                <li>Enter username &amp; password</li>
                <li>For contacts: Add CardDAV Account, same server</li>
              </ol>
            </div>
            <div>
              <p className="font-medium text-gray-900 mb-1">Android (DAVx⁵ app)</p>
              <ol className="list-decimal ml-4 space-y-0.5 text-xs text-gray-600">
                <li>Install DAVx⁵ from Play Store / F-Droid</li>
                <li>Login with URL: <span className="font-mono">http://{cellHost}/</span></li>
                <li>Select calendars &amp; address books to sync</li>
              </ol>
            </div>
            <div>
              <p className="font-medium text-gray-900 mb-1">Thunderbird</p>
              <ol className="list-decimal ml-4 space-y-0.5 text-xs text-gray-600">
                <li>Calendar → New Calendar → On the Network</li>
                <li>Format: CalDAV, Location: <span className="font-mono">http://{cellHost}/</span></li>
              </ol>
            </div>
          </div>
        </div>

        {/* Status */}
        <div className="card">
          <div className="flex items-center mb-4">
            <CalendarIcon className="h-6 w-6 text-primary-500 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Service Status</h3>
          </div>
          {status ? (
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-sm text-gray-500">Radicale:</span>
                <span className="text-sm font-medium text-success-600">Running</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-gray-500">CalDAV:</span>
                <span className="text-sm font-medium text-success-600">Active</span>
              </div>
              <div className="flex justify-between">
                <span className="text-sm text-gray-500">CardDAV:</span>
                <span className="text-sm font-medium text-success-600">Active</span>
              </div>
            </div>
          ) : (
            <p className="text-gray-500 text-sm">Status unavailable</p>
          )}
        </div>

        {/* Users */}
        <div className="card">
          <div className="flex items-center mb-4">
            <Users className="h-6 w-6 text-primary-500 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Calendar Users</h3>
          </div>
          <div className="space-y-2">
            {users.length > 0 ? (
              users.map((user, index) => (
                <div key={index} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                  <span className="text-sm font-medium">{user.username}</span>
                  <span className="text-sm text-gray-500">{user.calendars || 0} calendars</span>
                </div>
              ))
            ) : (
              <p className="text-gray-500 text-sm">No calendar users configured</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default Calendar;
