'use client'

import { useState, useEffect } from 'react'
import { 
  Calendar, Copy, Check, RefreshCw, 
  ExternalLink, HelpCircle, Smartphone 
} from 'lucide-react'

import { Card, Button, showToast } from '@/components/ui'

interface CalendarIntegrationProps {
  workspaceId: string
}

export function CalendarIntegration({ workspaceId }: CalendarIntegrationProps) {
  const [feed, setFeed] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [copied, setCopied] = useState(false)
  const [showInstructions, setShowInstructions] = useState(false)

  useEffect(() => {
    fetchFeed()
  }, [workspaceId])

  const fetchFeed = async () => {
    try {
      const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/settings`)
      if (response.ok) {
        const data = await response.json()
        setFeed(data.feed)
      }
    } catch (err) {
      console.error('Failed to fetch calendar feed:', err)
    } finally {
      setLoading(false)
    }
  }

  const createFeed = async () => {
    try {
      const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          includeAppointments: true,
          includeMeds: false,
          daysAhead: 90
        })
      })
      if (response.ok) {
        const data = await response.json()
        setFeed(data.feed)
        showToast('Calendar feed created!', 'success')
      }
    } catch {
      showToast('Failed to create feed', 'error')
    }
  }

  const regenerateToken = async () => {
    try {
      const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/regenerate`, {
        method: 'POST'
      })
      if (response.ok) {
        const data = await response.json()
        setFeed(data.feed)
        showToast('Feed URL regenerated', 'success')
      }
    } catch {
      showToast('Failed to regenerate', 'error')
    }
  }

  const copyFeedUrl = () => {
    if (!feed) return
    const url = `${window.location.origin}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token}`
    navigator.clipboard.writeText(url)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
    showToast('Feed URL copied!', 'success')
  }

  if (loading) {
    return (
      <Card className="text-center py-8">
        <div className="animate-spin w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full mx-auto" />
      </Card>
    )
  }

  return (
    <Card>
      <div className="flex items-center gap-3 mb-4">
        <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
          <Calendar className="w-5 h-5 text-blue-600" />
        </div>
        <div>
          <h3 className="font-semibold text-secondary-900">Calendar Integration</h3>
          <p className="text-sm text-secondary-500">Sync appointments to your calendar</p>
        </div>
      </div>

      {!feed ? (
        <div className="text-center py-6">
          <p className="text-secondary-500 mb-4">
            Create a calendar feed to see your appointments in Apple Calendar, Google Calendar, or Outlook.
          </p>
          <Button onClick={createFeed}>
            <Calendar className="w-4 h-4 mr-2" />
            Create Calendar Feed
          </Button>
        </div>
      ) : (
        <div className="space-y-4">
          {/* Feed URL */}
          <div>
            <label className="block text-sm font-medium text-secondary-700 mb-2">
              Calendar Feed URL
            </label>
            <div className="flex gap-2">
              <input
                type="text"
                value={`${typeof window !== 'undefined' ? window.location.origin : ''}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token.substring(0, 8)}...`}
                readOnly
                className="flex-1 px-3 py-2 bg-secondary-50 border border-border rounded-lg text-sm text-secondary-600"
              />
              <Button
                variant="secondary"
                onClick={copyFeedUrl}
                title="Copy URL"
              >
                {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
              </Button>
            </div>
            <p className="text-xs text-secondary-500 mt-1">
              Copy this URL and add it to your calendar app
            </p>
          </div>

          {/* Settings */}
          <div className="grid grid-cols-2 gap-4">
            <div className="p-3 bg-secondary-50 rounded-lg">
              <p className="text-xs text-secondary-500">Appointments</p>
              <p className="font-medium text-secondary-900">
                {feed.includeAppointments ? 'Included' : 'Not included'}
              </p>
            </div>
            <div className="p-3 bg-secondary-50 rounded-lg">
              <p className="text-xs text-secondary-500">Look Ahead</p>
              <p className="font-medium text-secondary-900">{feed.daysAhead} days</p>
            </div>
          </div>

          {/* Last Accessed */}
          {feed.lastAccessedAt && (
            <p className="text-xs text-secondary-500">
              Last accessed: {new Date(feed.lastAccessedAt).toLocaleDateString()}
            </p>
          )}

          {/* Actions */}
          <div className="flex gap-2 pt-2 border-t border-border">
            <Button
              variant="secondary"
              size="sm"
              onClick={() => setShowInstructions(!showInstructions)}
            >
              <HelpCircle className="w-4 h-4 mr-1" />
              How to Add
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={regenerateToken}
            >
              <RefreshCw className="w-4 h-4 mr-1" />
              Regenerate
            </Button>
          </div>

          {/* Instructions */}
          {showInstructions && (
            <div className="bg-blue-50 rounded-lg p-4 space-y-3">
              <h4 className="font-medium text-blue-900 flex items-center gap-2">
                <Smartphone className="w-4 h-4" />
                How to Add to Your Calendar
              </h4>
              
              <div className="space-y-3 text-sm text-blue-800">
                <div>
                  <p className="font-medium">Apple Calendar (iPhone/Mac):</p>
                  <ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
                    <li>Copy the feed URL above</li>
                    <li>Open Calendar app → File → New Calendar Subscription</li>
                    <li>Paste the URL and click Subscribe</li>
                  </ol>
                </div>
                
                <div>
                  <p className="font-medium">Google Calendar:</p>
                  <ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
                    <li>Copy the feed URL above</li>
                    <li>Open Google Calendar → Settings → Add Calendar → From URL</li>
                    <li>Paste the URL and click Add Calendar</li>
                  </ol>
                </div>
                
                <div>
                  <p className="font-medium">Outlook:</p>
                  <ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
                    <li>Copy the feed URL above</li>
                    <li>Open Outlook → Add Calendar → Subscribe from web</li>
                    <li>Paste the URL and click Import</li>
                  </ol>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </Card>
  )
}
