"use client"
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { Calendar, BarChart2, Settings, Bell, Trash2, Download } from 'lucide-react';

export default function SettingsPage() {
  const [reminderEnabled, setReminderEnabled] = useState(false);
  const [reminderTime, setReminderTime] = useState('23:00');
  
  useEffect(() => {
    const savedEnabled = localStorage.getItem('reminderEnabled') === 'true';
    const savedTime = localStorage.getItem('reminderTime') || '23:00';
    setReminderEnabled(savedEnabled);
    setReminderTime(savedTime);
  }, []);

  const handleReminderToggle = (enabled: boolean) => {
    setReminderEnabled(enabled);
    localStorage.setItem('reminderEnabled', String(enabled));
    if (enabled && 'Notification' in window) {
      Notification.requestPermission();
    }
  };

  const handleTimeChange = (time: string) => {
    setReminderTime(time);
    localStorage.setItem('reminderTime', time);
  };

  const exportCSV = async () => {
    const res = await fetch('/api/completions');
    const data = await res.json();
    if (!Array.isArray(data)) return;
    
    const headers = ['Date', 'Activity Name', 'Block Type', 'Start Time', 'End Time', 'Completed', 'Completed At'];
    const rows = data.map(c => [
      c.date, c.activityName, c.blockType, c.scheduledStart, c.scheduledEnd, c.completed, c.completedAt
    ]);
    
    const csvContent = [headers, ...rows].map(e => e.join(",")).join("\n");
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'task_history.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const clearHistory = async () => {
    if (confirm('Are you sure you want to completely delete your task completion history? This cannot be undone.')) {
      await fetch('/api/completions', { method: 'DELETE' });
      alert('History cleared.');
    }
  };

  return (
    <div className="max-w-4xl mx-auto pb-16 pt-4">
      <header className="flex justify-between items-center mb-8 px-4">
        <div>
          <h1 className="text-3xl font-bold text-slate-100">Settings</h1>
          <p className="text-slate-400 mt-1">Configure your reminders and manage data.</p>
        </div>
        <nav className="flex space-x-4">
          <Link href="/" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <Calendar size={18} /><span>සතිය (Week)</span>
          </Link>
          <Link href="/analytics" className="flex items-center space-x-2 px-4 py-2 hover:bg-slate-800 rounded-lg text-slate-300 transition-colors">
            <BarChart2 size={18} /><span>Analytics</span>
          </Link>
          <Link href="/settings" className="flex items-center space-x-2 px-4 py-2 bg-slate-800 rounded-lg text-blue-400 border border-blue-500/30">
            <Settings size={18} />
          </Link>
        </nav>
      </header>

      <div className="px-4 space-y-6">
        {/* Reminders Section */}
        <div className="bg-slate-900 border border-slate-800 p-6 rounded-2xl shadow-lg">
          <h3 className="text-lg font-semibold text-slate-200 mb-4 flex items-center space-x-2">
            <Bell size={20} className="text-blue-400" />
            <span>Daily Reminders</span>
          </h3>
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <p className="text-slate-400 text-sm">Enable browser notifications to remind you to check off tasks.</p>
            </div>
            <div className="flex items-center space-x-4">
              <input 
                type="time" 
                value={reminderTime}
                onChange={e => handleTimeChange(e.target.value)}
                className="bg-slate-800 border border-slate-700 text-slate-200 rounded-lg px-3 py-2 outline-none focus:border-blue-500"
              />
              <label className="relative inline-flex items-center cursor-pointer">
                <input type="checkbox" className="sr-only peer" checked={reminderEnabled} onChange={e => handleReminderToggle(e.target.checked)} />
                <div className="w-11 h-6 bg-slate-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
              </label>
            </div>
          </div>
        </div>

        {/* Data Management */}
        <div className="bg-slate-900 border border-slate-800 p-6 rounded-2xl shadow-lg">
          <h3 className="text-lg font-semibold text-slate-200 mb-4">Data Management</h3>
          <div className="flex flex-col space-y-4">
            <div className="flex items-center justify-between pb-4 border-b border-slate-800">
              <div>
                <p className="text-slate-300 font-medium">Export Analytics Data</p>
                <p className="text-slate-500 text-sm">Download your full completion history as a CSV file.</p>
              </div>
              <button onClick={exportCSV} className="flex items-center space-x-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg transition-colors">
                <Download size={18} /> <span>Export CSV</span>
              </button>
            </div>
            <div className="flex items-center justify-between pt-2">
              <div>
                <p className="text-slate-300 font-medium">Clear History</p>
                <p className="text-slate-500 text-sm">Permanently delete all task completion data.</p>
              </div>
              <button onClick={clearHistory} className="flex items-center space-x-2 px-4 py-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 rounded-lg transition-colors">
                <Trash2 size={18} /> <span>Clear Data</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
