'use client';

import React, { useState, useEffect } from 'react';
import {
  createAnnouncement,
  editAnnouncement,
  archiveAnnouncement,
  cancelScheduledAnnouncement,
  restoreAnnouncement,
  getAnnouncementsFeed,
  getAdminAnnouncementsList
} from '@/lib/actions/announcements';
import { getAnnouncementStatus } from '@/lib/announcement-helpers';
import { getCities, getAreas } from '@/lib/actions/geography';
import { getSatsangCentersDirectory } from '@/lib/actions/directory';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';
import { DateTime } from 'luxon';

export default function AnnouncementsPage() {
  const [feed, setFeed] = useState<any[]>([]);
  const [adminList, setAdminList] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState<'feed' | 'manage'>('feed');
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Form states
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  const [form, setForm] = useState({
    title: '',
    message: '',
    priority: 'Normal' as 'Normal' | 'Important' | 'Urgent',
    isGlobal: false,
    audienceType: 'everyone' as 'everyone' | 'geography' | 'centers',
    selectedCities: [] as string[],
    selectedAreas: [] as string[],
    selectedCenters: [] as string[],
    selectedRoles: [] as string[],
    publishDateTime: DateTime.now().setZone('Asia/Kolkata').toFormat("yyyy-MM-dd'T'HH:mm"),
    expiryDateTime: ''
  });

  // Geographies for filters
  const [cities, setCities] = useState<any[]>([]);
  const [areas, setAreas] = useState<any[]>([]);
  const [centers, setCenters] = useState<any[]>([]);

  useEffect(() => {
    loadFeed();
    loadGeographies();
  }, []);

  useEffect(() => {
    if (activeTab === 'manage') {
      loadAdminList();
    }
  }, [activeTab]);

  const loadFeed = async () => {
    setIsLoading(true);
    try {
      const data = await getAnnouncementsFeed();
      setFeed(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const loadAdminList = async () => {
    setIsLoading(true);
    try {
      const data = await getAdminAnnouncementsList();
      setAdminList(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const loadGeographies = async () => {
    try {
      const cList = await getCities('');
      setCities(cList);
      const cenList = await getSatsangCentersDirectory();
      setCenters(cenList);
    } catch (err) {
      console.error(err);
    }
  };

  const handleCitySelect = async (cId: string) => {
    if (!cId) return;
    if (form.selectedCities.includes(cId)) return;

    const newCities = [...form.selectedCities, cId];
    setForm(f => ({ ...f, selectedCities: newCities }));

    // Fetch areas for this city and merge
    const cityAreas = await getAreas(cId);
    setAreas(prev => {
      const merged = [...prev];
      cityAreas.forEach((a: any) => {
        if (!merged.some((m: any) => m._id === a._id)) merged.push(a);
      });
      return merged;
    });
  };

  const handleAreaSelect = (aId: string) => {
    if (!aId) return;
    if (form.selectedAreas.includes(aId)) return;
    setForm(f => ({ ...f, selectedAreas: [...f.selectedAreas, aId] }));
  };

  const handleCenterSelect = (cenId: string) => {
    if (!cenId) return;
    if (form.selectedCenters.includes(cenId)) return;
    setForm(f => ({ ...f, selectedCenters: [...f.selectedCenters, cenId] }));
  };

  const handleRoleToggle = (role: string) => {
    setForm(f => {
      const active = f.selectedRoles.includes(role);
      const roles = active ? f.selectedRoles.filter(r => r !== role) : [...f.selectedRoles, role];
      return { ...f, selectedRoles: roles };
    });
  };

  const handleOpenCreate = () => {
    setEditingId(null);
    setForm({
      title: '',
      message: '',
      priority: 'Normal',
      isGlobal: false,
      audienceType: 'everyone',
      selectedCities: [],
      selectedAreas: [],
      selectedCenters: [],
      selectedRoles: [],
      publishDateTime: DateTime.now().setZone('Asia/Kolkata').toFormat("yyyy-MM-dd'T'HH:mm"),
      expiryDateTime: ''
    });
    setError(null);
    setIsModalOpen(true);
  };

  const handleOpenEdit = (ann: any) => {
    setEditingId(ann._id);
    setError(null);

    // Prepopulate form fields
    const publishStr = DateTime.fromISO(ann.publishDateTime).setZone('Asia/Kolkata').toFormat("yyyy-MM-dd'T'HH:mm");
    const expiryStr = ann.expiryDateTime
      ? DateTime.fromISO(ann.expiryDateTime).setZone('Asia/Kolkata').toFormat("yyyy-MM-dd'T'HH:mm")
      : '';

    let audType: 'everyone' | 'geography' | 'centers' = 'everyone';
    if (ann.audience?.centerTargets?.length > 0) audType = 'centers';
    else if (ann.audience?.geographyTargets?.length > 0 || ann.audience?.roleFilters?.length > 0) audType = 'geography';

    setForm({
      title: ann.title,
      message: ann.message,
      priority: ann.priority,
      isGlobal: ann.isGlobal,
      audienceType: audType,
      selectedCities: ann.audience?.geographyTargets?.filter((t: any) => t.scopeType === 'City').map((t: any) => t.targetId) || [],
      selectedAreas: ann.audience?.geographyTargets?.filter((t: any) => t.scopeType === 'Area').map((t: any) => t.targetId) || [],
      selectedCenters: ann.audience?.centerTargets || [],
      selectedRoles: ann.audience?.roleFilters || [],
      publishDateTime: publishStr,
      expiryDateTime: expiryStr
    });
    setIsModalOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    setError(null);

    // Map targets to audience structure
    const geoTargets: any[] = [];
    form.selectedCities.forEach(cId => {
      geoTargets.push({ scopeType: 'City', targetId: cId });
    });
    form.selectedAreas.forEach(aId => {
      geoTargets.push({ scopeType: 'Area', targetId: aId });
    });

    const audience = {
      geographyTargets: form.isGlobal ? [] : geoTargets,
      centerTargets: form.isGlobal ? [] : form.selectedCenters,
      roleFilters: form.isGlobal ? [] : form.selectedRoles
    };

    const payload = {
      title: form.title,
      message: form.message,
      priority: form.priority,
      isGlobal: form.isGlobal,
      audience,
      publishDateTime: new Date(form.publishDateTime).toISOString(),
      expiryDateTime: form.expiryDateTime ? new Date(form.expiryDateTime).toISOString() : undefined
    };

    try {
      if (editingId) {
        await editAnnouncement(editingId, payload);
        setSuccess('Announcement updated successfully!');
      } else {
        await createAnnouncement(payload);
        setSuccess('Announcement published successfully!');
      }
      setIsModalOpen(false);
      if (activeTab === 'feed') loadFeed();
      else loadAdminList();
    } catch (err: any) {
      setError(err.message || 'An error occurred during publication');
    } finally {
      setIsSaving(false);
    }
  };

  const handleArchive = async (id: string) => {
    if (!confirm('Are you sure you want to archive this announcement?')) return;
    try {
      await archiveAnnouncement(id);
      setSuccess('Announcement archived successfully.');
      loadAdminList();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleCancelScheduled = async (id: string) => {
    if (!confirm('Are you sure you want to cancel this scheduled announcement?')) return;
    try {
      await cancelScheduledAnnouncement(id);
      setSuccess('Scheduled publication cancelled.');
      loadAdminList();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleRestore = async (id: string) => {
    try {
      await restoreAnnouncement(id);
      setSuccess('Announcement restored successfully.');
      loadAdminList();
    } catch (err: any) {
      setError(err.message);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-gray-900 font-sans">Satsang Announcements</h1>
          <p className="mt-1 text-sm text-gray-500">View or publish community announcements to parivar leaders.</p>
        </div>
        <Button onClick={handleOpenCreate} className="bg-brand-primary text-white text-xs py-2 px-4 shadow">
          + Create Announcement
        </Button>
      </div>

      {success && (
        <div className="bg-green-50 border border-green-200 text-green-800 p-4 rounded-xl text-sm font-semibold flex items-center justify-between">
          <span>{success}</span>
          <button onClick={() => setSuccess(null)} className="text-green-500 hover:text-green-700 font-bold ml-2">Dismiss</button>
        </div>
      )}

      {/* Tabs */}
      <div className="flex border-b border-gray-250">
        <button
          onClick={() => { setActiveTab('feed'); setError(null); }}
          className={`py-3 px-6 font-bold text-sm border-b-2 transition-all ${
            activeTab === 'feed' ? 'border-brand-primary text-brand-primary' : 'border-transparent text-gray-500 hover:text-gray-900'
          }`}
        >
          My Feed
        </button>
        <button
          onClick={() => { setActiveTab('manage'); setError(null); }}
          className={`py-3 px-6 font-bold text-sm border-b-2 transition-all ${
            activeTab === 'manage' ? 'border-brand-primary text-brand-primary' : 'border-transparent text-gray-500 hover:text-gray-900'
          }`}
        >
          Manage Publications
        </button>
      </div>

      {isLoading ? (
        <div className="text-center py-20">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-primary mx-auto"></div>
          <p className="mt-2 text-xs text-gray-500 font-semibold">Retrieving announcements...</p>
        </div>
      ) : activeTab === 'feed' ? (
        /* My Feed List */
        <div className="space-y-4 max-w-3xl">
          {feed.length === 0 ? (
            <div className="text-center py-12 text-gray-500 text-sm font-semibold bg-white p-6 rounded-xl border border-gray-150 shadow-sm">
              No active announcements in your feed right now.
            </div>
          ) : (
            feed.map((ann) => (
              <Card key={ann._id} className={`p-6 border-l-4 ${
                ann.priority === 'Urgent' ? 'border-l-red-500 bg-red-50/10' :
                ann.priority === 'Important' ? 'border-l-orange-500 bg-orange-50/5' :
                'border-l-gray-300'
              }`}>
                <div className="flex justify-between items-start gap-4">
                  <div>
                    <div className="flex items-center gap-2 flex-wrap">
                      <h3 className="text-lg font-extrabold text-gray-950">{ann.title}</h3>
                      {ann.priority !== 'Normal' && (
                        <span className={`text-[9px] font-bold px-2 py-0.5 rounded-full ${
                          ann.priority === 'Urgent' ? 'bg-red-100 text-red-700' : 'bg-orange-100 text-orange-700'
                        }`}>
                          {ann.priority}
                        </span>
                      )}
                    </div>
                    <span className="text-[10px] text-gray-400 font-bold block mt-1">
                      Published {DateTime.fromISO(ann.publishDateTime).toFormat('dd LLL yyyy, hh:mm a')} • By {ann.createdBy?.email}
                    </span>
                  </div>
                </div>
                <p className="mt-4 text-sm text-gray-800 leading-relaxed whitespace-pre-wrap">{ann.message}</p>
              </Card>
            ))
          )}
        </div>
      ) : (
        /* Manage Feed */
        <Card className="p-6">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 text-left text-sm">
              <thead className="bg-gray-50 text-xs font-bold text-gray-500 uppercase tracking-wider">
                <tr>
                  <th className="px-4 py-3">Title</th>
                  <th className="px-4 py-3">Priority</th>
                  <th className="px-4 py-3">Publish Date</th>
                  <th className="px-4 py-3">Status</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-150">
                {adminList.map((ann) => {
                  const status = getAnnouncementStatus(ann);
                  return (
                    <tr key={ann._id} className="hover:bg-gray-50/50">
                      <td className="px-4 py-3 font-bold text-gray-950">{ann.title}</td>
                      <td className="px-4 py-3">
                        <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                          ann.priority === 'Urgent' ? 'bg-red-100 text-red-700' :
                          ann.priority === 'Important' ? 'bg-orange-100 text-orange-700' :
                          'bg-gray-100 text-gray-700'
                        }`}>
                          {ann.priority}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-xs">
                        {DateTime.fromISO(ann.publishDateTime).toFormat('dd LLL yyyy, hh:mm a')}
                      </td>
                      <td className="px-4 py-3 text-xs font-bold">
                        <span className={`px-2 py-0.5 rounded-full ${
                          status === 'Published' ? 'bg-green-100 text-green-700' :
                          status === 'Scheduled' ? 'bg-blue-100 text-blue-700' :
                          status === 'Expired' ? 'bg-yellow-100 text-yellow-700' :
                          'bg-gray-100 text-gray-700'
                        }`}>
                          {status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right space-x-2">
                        {status !== 'Archived' && (
                          <Button onClick={() => handleOpenEdit(ann)} variant="secondary" className="py-1 px-2.5 text-[10px] border-gray-250">
                            Edit
                          </Button>
                        )}
                        {status === 'Scheduled' && (
                          <Button onClick={() => handleCancelScheduled(ann._id)} className="bg-yellow-600 hover:bg-yellow-700 text-white py-1 px-2.5 text-[10px]">
                            Cancel Pub
                          </Button>
                        )}
                        {status !== 'Archived' && status !== 'Scheduled' && (
                          <Button onClick={() => handleArchive(ann._id)} className="bg-red-600 hover:bg-red-700 text-white py-1 px-2.5 text-[10px]">
                            Archive
                          </Button>
                        )}
                        {status === 'Archived' && (
                          <Button onClick={() => handleRestore(ann._id)} className="bg-green-600 hover:bg-green-700 text-white py-1 px-2.5 text-[10px]">
                            Restore
                          </Button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* --- CREATE / EDIT MODAL --- */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-gray-600 bg-opacity-75" onClick={() => setIsModalOpen(false)} />

          <div className="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-6 border border-gray-150 animate-slide-in max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-bold text-gray-950 mb-4">
              {editingId ? 'Edit Announcement' : 'Publish Announcement'}
            </h3>

            {error && (
              <div className="bg-red-50 border border-red-200 text-red-800 p-3 rounded-lg text-xs font-semibold mb-4">
                {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Title</label>
                <Input required value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
              </div>

              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Message</label>
                <textarea
                  required
                  rows={4}
                  value={form.message}
                  onChange={(e) => setForm({ ...form, message: e.target.value })}
                  className="w-full rounded-lg border border-gray-250 p-2.5 text-sm bg-white focus:outline-none"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Priority</label>
                  <select
                    value={form.priority}
                    onChange={(e) => setForm({ ...form, priority: e.target.value as any })}
                    className="w-full rounded-lg border border-gray-250 p-2 bg-white text-sm"
                  >
                    <option value="Normal">Normal</option>
                    <option value="Important">Important</option>
                    <option value="Urgent">Urgent</option>
                  </select>
                </div>

                <div className="flex items-center gap-2 pt-6">
                  <input
                    type="checkbox"
                    id="isGlobalCheck"
                    checked={form.isGlobal}
                    onChange={(e) => setForm({ ...form, isGlobal: e.target.checked })}
                    className="rounded border-gray-300 text-brand-primary h-5 w-5 focus:ring-0"
                  />
                  <label htmlFor="isGlobalCheck" className="text-xs font-bold text-gray-500 uppercase tracking-wider">
                    Global (Everyone)
                  </label>
                </div>
              </div>

              {!form.isGlobal && (
                <div className="space-y-3 p-3 bg-gray-50 border border-gray-150 rounded-lg">
                  <h4 className="text-xs font-bold text-gray-700">Audience Filters</h4>

                  <div className="grid grid-cols-2 gap-2">
                    {/* Add City Selector */}
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase">Target Cities</label>
                      <select
                        onChange={(e) => handleCitySelect(e.target.value)}
                        className="w-full rounded border border-gray-200 p-1 bg-white text-[10px]"
                        value=""
                      >
                        <option value="">Select City...</option>
                        {cities.map((c) => <option key={c._id} value={c._id}>{c.name}</option>)}
                      </select>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {form.selectedCities.map(cId => {
                          const name = cities.find(c => c._id === cId)?.name || 'City';
                          return (
                            <span key={cId} className="text-[9px] bg-white border px-1 rounded flex items-center gap-1 font-bold">
                              {name}
                              <button type="button" onClick={() => setForm(f => ({ ...f, selectedCities: f.selectedCities.filter(id => id !== cId) }))} className="text-red-500 font-black">×</button>
                            </span>
                          );
                        })}
                      </div>
                    </div>

                    {/* Add Area Selector */}
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase">Target Areas</label>
                      <select
                        onChange={(e) => handleAreaSelect(e.target.value)}
                        className="w-full rounded border border-gray-200 p-1 bg-white text-[10px]"
                        value=""
                        disabled={form.selectedCities.length === 0}
                      >
                        <option value="">Select Area...</option>
                        {areas.map((a) => <option key={a._id} value={a._id}>{a.name}</option>)}
                      </select>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {form.selectedAreas.map(aId => {
                          const name = areas.find(a => a._id === aId)?.name || 'Area';
                          return (
                            <span key={aId} className="text-[9px] bg-white border px-1 rounded flex items-center gap-1 font-bold">
                              {name}
                              <button type="button" onClick={() => setForm(f => ({ ...f, selectedAreas: f.selectedAreas.filter(id => id !== aId) }))} className="text-red-500 font-black">×</button>
                            </span>
                          );
                        })}
                      </div>
                    </div>
                  </div>

                  {/* Role targeted checkboxes */}
                  <div>
                    <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Target Roles</label>
                    <div className="flex gap-4 text-xs font-semibold text-gray-700">
                      <label className="flex items-center gap-1.5">
                        <input type="checkbox" checked={form.selectedRoles.includes('CITY_HEAD')} onChange={() => handleRoleToggle('CITY_HEAD')} className="rounded text-brand-primary" />
                        City Heads
                      </label>
                      <label className="flex items-center gap-1.5">
                        <input type="checkbox" checked={form.selectedRoles.includes('AREA_INCHARGE')} onChange={() => handleRoleToggle('AREA_INCHARGE')} className="rounded text-brand-primary" />
                        Area Incharges
                      </label>
                    </div>
                  </div>

                  {/* Centers targets */}
                  <div>
                    <label className="block text-[10px] font-bold text-gray-400 uppercase">Target Centers</label>
                    <select
                      onChange={(e) => handleCenterSelect(e.target.value)}
                      className="w-full rounded border border-gray-200 p-1 bg-white text-[10px]"
                      value=""
                    >
                      <option value="">Select Center...</option>
                      {centers.map((c) => <option key={c._id} value={c._id}>{c.name}</option>)}
                    </select>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {form.selectedCenters.map(cenId => {
                        const name = centers.find(c => c._id === cenId)?.name || 'Center';
                        return (
                          <span key={cenId} className="text-[9px] bg-white border px-1 rounded flex items-center gap-1 font-bold">
                            {name}
                            <button type="button" onClick={() => setForm(f => ({ ...f, selectedCenters: f.selectedCenters.filter(id => id !== cenId) }))} className="text-red-500 font-black">×</button>
                          </span>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Publish Date/Time</label>
                  <Input type="datetime-local" value={form.publishDateTime} onChange={(e) => setForm({ ...form, publishDateTime: e.target.value })} />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Expiry Date/Time (Optional)</label>
                  <Input type="datetime-local" value={form.expiryDateTime} onChange={(e) => setForm({ ...form, expiryDateTime: e.target.value })} />
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-4 border-t border-gray-150">
                <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)}>
                  Cancel
                </Button>
                <Button type="submit" isLoading={isSaving} className="bg-brand-primary text-white">
                  Publish Announcement
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
