'use client';

import { useState, useEffect } from 'react';
import { useAdminAuth } from '@/hooks/useAdminAuth';
import { AdminSidebar } from '@/components/admin-sidebar';
import { 
  Building2, 
  MapPin, 
  Phone, 
  Mail, 
  Globe, 
  User, 
  Plus,
  Edit,
  Trash2,
  Shield,
  Users,
  ChevronDown,
  ChevronUp,
  Upload,
  Image
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from 'sonner';

interface Polres {
  id: string;
  name: string;
  address: string;
  phone?: string;
  email?: string;
  website?: string;
  fax?: string;
  description?: string;
  logo?: string;
  photo?: string;
  kapolresName?: string;
  kapolresNRP?: string;
  kapolresPangkat?: string;
  isActive: boolean;
  order: number;
  polseks: Polsek[];
  createdAt: string;
  updatedAt: string;
}

interface Polsek {
  id: string;
  name: string;
  address: string;
  phone?: string;
  email?: string;
  website?: string;
  fax?: string;
  description?: string;
  photo?: string;
  kapolsekName?: string;
  kapolsekNRP?: string;
  kapolsekPangkat?: string;
  isActive: boolean;
  order: number;
  polresId: string;
  polres: {
    id: string;
    name: string;
  };
  createdAt: string;
  updatedAt: string;
}

export default function PoliceManagementPage() {
  const { user, loading: authLoading } = useAdminAuth();
  const [activeTab, setActiveTab] = useState<'polres' | 'polsek'>('polres');
  const [polresList, setPolresList] = useState<Polres[]>([]);
  const [polsekList, setPolsekList] = useState<Polsek[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [expandedPolres, setExpandedPolres] = useState<string[]>([]);

  // Form states
  const [isPolresDialogOpen, setIsPolresDialogOpen] = useState(false);
  const [isPolsekDialogOpen, setIsPolsekDialogOpen] = useState(false);
  const [editingPolres, setEditingPolres] = useState<Polres | null>(null);
  const [editingPolsek, setEditingPolsek] = useState<Polsek | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{ type: 'polres' | 'polsek'; id: string; name: string } | null>(null);

  const [polresForm, setPolresForm] = useState({
    name: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    fax: '',
    description: '',
    logo: '',
    photo: '',
    kapolresName: '',
    kapolresNRP: '',
    kapolresPangkat: ''
  });

  const [polsekForm, setPolsekForm] = useState({
    name: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    fax: '',
    description: '',
    photo: '',
    kapolsekName: '',
    kapolsekNRP: '',
    kapolsekPangkat: '',
    polresId: ''
  });

  useEffect(() => {
    if (!authLoading && user) {
      fetchData();
    }
  }, [authLoading, user]);

  const fetchData = async () => {
    try {
      setLoading(true);
      
      // Get auth headers
      const token = localStorage.getItem('adminToken');
      const headers = {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      };
      
      // Fetch Polres data
      const polresResponse = await fetch('/api/admin/polres', {
        headers
      });
      if (polresResponse.ok) {
        const polresData = await polresResponse.json();
        setPolresList(polresData.data);
      } else {
        console.error('Polres API error:', polresResponse.status);
      }

      // Fetch Polsek data
      const polsekResponse = await fetch('/api/admin/polsek', {
        headers
      });
      if (polsekResponse.ok) {
        const polsekData = await polsekResponse.json();
        setPolsekList(polsekData.data);
      } else {
        console.error('Polsek API error:', polsekResponse.status);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Gagal mengambil data');
    } finally {
      setLoading(false);
    }
  };

  const resetPolresForm = () => {
    setPolresForm({
      name: '',
      address: '',
      phone: '',
      email: '',
      website: '',
      fax: '',
      description: '',
      logo: '',
      photo: '',
      kapolresName: '',
      kapolresNRP: '',
      kapolresPangkat: ''
    });
    setEditingPolres(null);
  };

  const resetPolsekForm = () => {
    setPolsekForm({
      name: '',
      address: '',
      phone: '',
      email: '',
      website: '',
      fax: '',
      description: '',
      photo: '',
      kapolsekName: '',
      kapolsekNRP: '',
      kapolsekPangkat: '',
      polresId: ''
    });
    setEditingPolsek(null);
  };

  const handleFileUpload = async (file: File, type: 'logo' | 'photo') => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', type);

      const token = localStorage.getItem('adminToken');
      const response = await fetch('/api/admin/upload', {
        method: 'POST',
        headers: {
          ...(token && { 'Authorization': `Bearer ${token}` })
        },
        body: formData,
      });

      const data = await response.json();
      if (data.success) {
        return data.url;
      } else {
        throw new Error(data.error || 'Upload failed');
      }
    } catch (error) {
      console.error('File upload error:', error);
      throw error;
    }
  };

  const handlePolresSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const url = editingPolres ? `/api/admin/polres/${editingPolres.id}` : '/api/admin/polres';
      const method = editingPolres ? 'PUT' : 'POST';
      
      // Get auth headers
      const token = localStorage.getItem('adminToken');
      const headers = {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      };

      const response = await fetch(url, {
        method,
        headers,
        body: JSON.stringify(polresForm),
      });

      const data = await response.json();

      if (data.success) {
        toast.success(data.message);
        setIsPolresDialogOpen(false);
        resetPolresForm();
        fetchData();
      } else {
        toast.error(data.message);
      }
    } catch (error) {
      console.error('Error submitting Polres:', error);
      toast.error('Terjadi kesalahan saat menyimpan data');
    } finally {
      setSubmitting(false);
    }
  };

  const handlePolsekSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const url = editingPolsek ? `/api/admin/polsek/${editingPolsek.id}` : '/api/admin/polsek';
      const method = editingPolsek ? 'PUT' : 'POST';
      
      // Get auth headers
      const token = localStorage.getItem('adminToken');
      const headers = {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      };

      const response = await fetch(url, {
        method,
        headers,
        body: JSON.stringify(polsekForm),
      });

      const data = await response.json();

      if (data.success) {
        toast.success(data.message);
        setIsPolsekDialogOpen(false);
        resetPolsekForm();
        fetchData();
      } else {
        toast.error(data.message);
      }
    } catch (error) {
      console.error('Error submitting Polsek:', error);
      toast.error('Terjadi kesalahan saat menyimpan data');
    } finally {
      setSubmitting(false);
    }
  };

  const handleEditPolres = (polres: Polres) => {
    setEditingPolres(polres);
    setPolresForm({
      name: polres.name,
      address: polres.address,
      phone: polres.phone || '',
      email: polres.email || '',
      website: polres.website || '',
      fax: polres.fax || '',
      description: polres.description || '',
      logo: polres.logo || '',
      photo: polres.photo || '',
      kapolresName: polres.kapolresName || '',
      kapolresNRP: polres.kapolresNRP || '',
      kapolresPangkat: polres.kapolresPangkat || ''
    });
    setIsPolresDialogOpen(true);
  };

  const handleEditPolsek = (polsek: Polsek) => {
    setEditingPolsek(polsek);
    setPolsekForm({
      name: polsek.name,
      address: polsek.address,
      phone: polsek.phone || '',
      email: polsek.email || '',
      website: polsek.website || '',
      fax: polsek.fax || '',
      description: polsek.description || '',
      photo: polsek.photo || '',
      kapolsekName: polsek.kapolsekName || '',
      kapolsekNRP: polsek.kapolsekNRP || '',
      kapolsekPangkat: polsek.kapolsekPangkat || '',
      polresId: polsek.polresId
    });
    setIsPolsekDialogOpen(true);
  };

  const handleDelete = async () => {
    if (!deleteConfirm) return;

    try {
      const url = deleteConfirm.type === 'polres' 
        ? `/api/admin/polres/${deleteConfirm.id}`
        : `/api/admin/polsek/${deleteConfirm.id}`;
      
      // Get auth headers
      const token = localStorage.getItem('adminToken');
      const headers = {
        'Content-Type': 'application/json',
        ...(token && { 'Authorization': `Bearer ${token}` })
      };

      const response = await fetch(url, {
        method: 'DELETE',
        headers,
      });

      const data = await response.json();

      if (data.success) {
        toast.success(data.message);
        fetchData();
      } else {
        toast.error(data.message);
      }
    } catch (error) {
      console.error('Error deleting:', error);
      toast.error('Terjadi kesalahan saat menghapus data');
    } finally {
      setDeleteConfirm(null);
    }
  };

  const togglePolresExpansion = (polresId: string) => {
    setExpandedPolres(prev => 
      prev.includes(polresId) 
        ? prev.filter(id => id !== polresId)
        : [...prev, polresId]
    );
  };

  if (authLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return null;
  }

  return (
    <AdminSidebar user={user}>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">Manajemen Kepolisian</h1>
            <p className="text-muted-foreground">Kelola data Polres dan Polsek</p>
          </div>
        </div>

        {/* Tab Navigation */}
        <div className="flex space-x-1 bg-muted p-1 rounded-lg w-fit">
          <Button
            variant={activeTab === 'polres' ? 'default' : 'ghost'}
            onClick={() => setActiveTab('polres')}
            className="flex items-center space-x-2"
          >
            <Building2 className="h-4 w-4" />
            <span>Polres</span>
          </Button>
          <Button
            variant={activeTab === 'polsek' ? 'default' : 'ghost'}
            onClick={() => setActiveTab('polsek')}
            className="flex items-center space-x-2"
          >
            <Users className="h-4 w-4" />
            <span>Polsek</span>
          </Button>
        </div>

      {activeTab === 'polres' && (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-semibold">Data Polres</h2>
            <Dialog open={isPolresDialogOpen} onOpenChange={setIsPolresDialogOpen}>
              <DialogTrigger asChild>
                <Button onClick={resetPolresForm}>
                  <Plus className="h-4 w-4 mr-2" />
                  Tambah Polres
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>
                    {editingPolres ? 'Edit Polres' : 'Tambah Polres Baru'}
                  </DialogTitle>
                  <DialogDescription>
                    {editingPolres ? 'Perbarui data Polres' : 'Masukkan data Polres baru'}
                  </DialogDescription>
                </DialogHeader>
                <form onSubmit={handlePolresSubmit} className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="name">Nama Polres *</Label>
                      <Input
                        id="name"
                        value={polresForm.name}
                        onChange={(e) => setPolresForm(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="Contoh: Polres Wonosobo"
                        required
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="phone">Telepon</Label>
                      <Input
                        id="phone"
                        value={polresForm.phone}
                        onChange={(e) => setPolresForm(prev => ({ ...prev, phone: e.target.value }))}
                        placeholder="Contoh: (0286) 321001"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="address">Alamat *</Label>
                    <Textarea
                      id="address"
                      value={polresForm.address}
                      onChange={(e) => setPolresForm(prev => ({ ...prev, address: e.target.value }))}
                      placeholder="Masukkan alamat lengkap"
                      required
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="email">Email</Label>
                      <Input
                        id="email"
                        type="email"
                        value={polresForm.email}
                        onChange={(e) => setPolresForm(prev => ({ ...prev, email: e.target.value }))}
                        placeholder="polres@example.com"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="website">Website</Label>
                      <Input
                        id="website"
                        value={polresForm.website}
                        onChange={(e) => setPolresForm(prev => ({ ...prev, website: e.target.value }))}
                        placeholder="https://polres.example.com"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="description">Deskripsi</Label>
                    <Textarea
                      id="description"
                      value={polresForm.description}
                      onChange={(e) => setPolresForm(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="Deskripsi singkat tentang Polres"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="logo">Logo Polres</Label>
                      <div className="flex items-center space-x-2">
                        <Input
                          id="logo"
                          type="file"
                          accept="image/*"
                          onChange={async (e) => {
                            const file = e.target.files?.[0];
                            if (file) {
                              try {
                                toast.loading('Mengupload logo...');
                                const url = await handleFileUpload(file, 'logo');
                                setPolresForm(prev => ({ ...prev, logo: url }));
                                toast.success('Logo berhasil diupload');
                              } catch (error) {
                                toast.error('Gagal upload logo');
                              }
                            }
                          }}
                          className="file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-sm file:bg-amber-50 file:text-amber-700 hover:file:bg-amber-100"
                        />
                        {polresForm.logo && (
                          <div className="flex items-center space-x-2">
                            <Image className="h-4 w-4 text-green-600" alt="Logo uploaded icon" />
                            <span className="text-sm text-green-600">Logo terupload</span>
                          </div>
                        )}
                      </div>
                      {polresForm.logo && (
                        <div className="mt-2">
                          <img 
                            src={polresForm.logo} 
                            alt="Logo Polres preview" 
                            className="h-16 w-auto object-contain border rounded"
                          />
                        </div>
                      )}
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="photo">Foto Gedung</Label>
                      <div className="flex items-center space-x-2">
                        <Input
                          id="photo"
                          type="file"
                          accept="image/*"
                          onChange={async (e) => {
                            const file = e.target.files?.[0];
                            if (file) {
                              try {
                                toast.loading('Mengupload foto...');
                                const url = await handleFileUpload(file, 'photo');
                                setPolresForm(prev => ({ ...prev, photo: url }));
                                toast.success('Foto berhasil diupload');
                              } catch (error) {
                                toast.error('Gagal upload foto');
                              }
                            }
                          }}
                          className="file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-sm file:bg-amber-50 file:text-amber-700 hover:file:bg-amber-100"
                        />
                        {polresForm.photo && (
                          <div className="flex items-center space-x-2">
                            <Image className="h-4 w-4 text-green-600" alt="Photo uploaded icon" />
                            <span className="text-sm text-green-600">Foto terupload</span>
                          </div>
                        )}
                      </div>
                      {polresForm.photo && (
                        <div className="mt-2">
                          <img 
                            src={polresForm.photo} 
                            alt="Foto Gedung Polres preview" 
                            className="h-16 w-auto object-contain border rounded"
                          />
                        </div>
                      )}
                    </div>
                  </div>

                  <div className="border-t pt-4">
                    <h3 className="font-medium mb-4">Data Kapolres</h3>
                    <div className="grid grid-cols-3 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="kapolresName">Nama Kapolres</Label>
                        <Input
                          id="kapolresName"
                          value={polresForm.kapolresName}
                          onChange={(e) => setPolresForm(prev => ({ ...prev, kapolresName: e.target.value }))}
                          placeholder="Nama lengkap"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="kapolresNRP">NRP</Label>
                        <Input
                          id="kapolresNRP"
                          value={polresForm.kapolresNRP}
                          onChange={(e) => setPolresForm(prev => ({ ...prev, kapolresNRP: e.target.value }))}
                          placeholder="Nomor Register Polisi"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="kapolresPangkat">Pangkat</Label>
                        <Input
                          id="kapolresPangkat"
                          value={polresForm.kapolresPangkat}
                          onChange={(e) => setPolresForm(prev => ({ ...prev, kapolresPangkat: e.target.value }))}
                          placeholder="Contoh: AKBP"
                        />
                      </div>
                    </div>
                  </div>

                  <DialogFooter>
                    <Button type="button" variant="outline" onClick={() => setIsPolresDialogOpen(false)}>
                      Batal
                    </Button>
                    <Button type="submit" disabled={submitting}>
                      {submitting ? 'Menyimpan...' : (editingPolres ? 'Perbarui' : 'Simpan')}
                    </Button>
                  </DialogFooter>
                </form>
              </DialogContent>
            </Dialog>
          </div>

          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
              <p className="mt-2 text-muted-foreground">Memuat data...</p>
            </div>
          ) : polresList.length === 0 ? (
            <Alert>
              <AlertDescription>
                Belum ada data Polres. Klik "Tambah Polres" untuk menambahkan data pertama.
              </AlertDescription>
            </Alert>
          ) : (
            <div className="space-y-4">
              {polresList.map((polres) => (
                <Card key={polres.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <Building2 className="h-5 w-5 text-primary" />
                        <div>
                          <CardTitle className="text-lg">{polres.name}</CardTitle>
                          <CardDescription className="flex items-center space-x-2 mt-1">
                            <MapPin className="h-3 w-3" />
                            <span>{polres.address}</span>
                          </CardDescription>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => togglePolresExpansion(polres.id)}
                        >
                          {expandedPolres.includes(polres.id) ? (
                            <ChevronUp className="h-4 w-4" />
                          ) : (
                            <ChevronDown className="h-4 w-4" />
                          )}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleEditPolres(polres)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setDeleteConfirm({ type: 'polres', id: polres.id, name: polres.name })}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  {expandedPolres.includes(polres.id) && (
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        {polres.phone && (
                          <div className="flex items-center space-x-2">
                            <Phone className="h-4 w-4 text-muted-foreground" />
                            <span className="text-sm">{polres.phone}</span>
                          </div>
                        )}
                        {polres.email && (
                          <div className="flex items-center space-x-2">
                            <Mail className="h-4 w-4 text-muted-foreground" />
                            <span className="text-sm">{polres.email}</span>
                          </div>
                        )}
                        {polres.website && (
                          <div className="flex items-center space-x-2">
                            <Globe className="h-4 w-4 text-muted-foreground" />
                            <span className="text-sm">{polres.website}</span>
                          </div>
                        )}
                        {polres.fax && (
                          <div className="flex items-center space-x-2">
                            <span className="text-sm">Fax: {polres.fax}</span>
                          </div>
                        )}
                      </div>

                      {polres.description && (
                        <p className="text-sm text-muted-foreground">{polres.description}</p>
                      )}

                      {(polres.kapolresName || polres.kapolresNRP || polres.kapolresPangkat) && (
                        <div className="border-t pt-4">
                          <div className="flex items-center space-x-2 mb-2">
                            <Shield className="h-4 w-4" />
                            <span className="font-medium text-sm">Kapolres</span>
                          </div>
                          <div className="grid grid-cols-3 gap-4 text-sm">
                            {polres.kapolresName && (
                              <div>
                                <span className="font-medium">Nama:</span> {polres.kapolresName}
                              </div>
                            )}
                            {polres.kapolresNRP && (
                              <div>
                                <span className="font-medium">NRP:</span> {polres.kapolresNRP}
                              </div>
                            )}
                            {polres.kapolresPangkat && (
                              <div>
                                <span className="font-medium">Pangkat:</span> {polres.kapolresPangkat}
                              </div>
                            )}
                          </div>
                        </div>
                      )}

                      <div className="border-t pt-4">
                        <div className="flex items-center justify-between mb-3">
                          <span className="font-medium text-sm">
                            Polsek ({polres.polseks.length})
                          </span>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              setPolsekForm(prev => ({ ...prev, polresId: polres.id }));
                              setIsPolsekDialogOpen(true);
                            }}
                          >
                            <Plus className="h-3 w-3 mr-1" />
                            Tambah Polsek
                          </Button>
                        </div>
                        {polres.polseks.length === 0 ? (
                          <p className="text-sm text-muted-foreground">Belum ada Polsek</p>
                        ) : (
                          <div className="space-y-2">
                            {polres.polseks.map((polsek) => (
                              <div key={polsek.id} className="flex items-center justify-between p-3 bg-muted rounded-lg">
                                <div className="flex items-center space-x-3">
                                  <Building2 className="h-4 w-4 text-muted-foreground" />
                                  <div>
                                    <p className="font-medium text-sm">{polsek.name}</p>
                                    <p className="text-xs text-muted-foreground">{polsek.address}</p>
                                  </div>
                                </div>
                                <div className="flex items-center space-x-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleEditPolsek(polsek)}
                                  >
                                    <Edit className="h-3 w-3" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => setDeleteConfirm({ type: 'polsek', id: polsek.id, name: polsek.name })}
                                  >
                                    <Trash2 className="h-3 w-3" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </CardContent>
                  )}
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === 'polsek' && (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-semibold">Data Polsek</h2>
            <Dialog open={isPolsekDialogOpen} onOpenChange={setIsPolsekDialogOpen}>
              <DialogTrigger asChild>
                <Button onClick={resetPolsekForm}>
                  <Plus className="h-4 w-4 mr-2" />
                  Tambah Polsek
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>
                    {editingPolsek ? 'Edit Polsek' : 'Tambah Polsek Baru'}
                  </DialogTitle>
                  <DialogDescription>
                    {editingPolsek ? 'Perbarui data Polsek' : 'Masukkan data Polsek baru'}
                  </DialogDescription>
                </DialogHeader>
                <form onSubmit={handlePolsekSubmit} className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="polsekName">Nama Polsek *</Label>
                      <Input
                        id="polsekName"
                        value={polsekForm.name}
                        onChange={(e) => setPolsekForm(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="Contoh: Polsek Wonosobo"
                        required
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="polresId">Polres *</Label>
                      <Select
                        value={polsekForm.polresId}
                        onValueChange={(value) => setPolsekForm(prev => ({ ...prev, polresId: value }))}
                        required
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Pilih Polres" />
                        </SelectTrigger>
                        <SelectContent>
                          {polresList.map((polres) => (
                            <SelectItem key={polres.id} value={polres.id}>
                              {polres.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="polsekAddress">Alamat *</Label>
                    <Textarea
                      id="polsekAddress"
                      value={polsekForm.address}
                      onChange={(e) => setPolsekForm(prev => ({ ...prev, address: e.target.value }))}
                      placeholder="Masukkan alamat lengkap"
                      required
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="polsekPhone">Telepon</Label>
                      <Input
                        id="polsekPhone"
                        value={polsekForm.phone}
                        onChange={(e) => setPolsekForm(prev => ({ ...prev, phone: e.target.value }))}
                        placeholder="Contoh: (0286) 321002"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="polsekEmail">Email</Label>
                      <Input
                        id="polsekEmail"
                        type="email"
                        value={polsekForm.email}
                        onChange={(e) => setPolsekForm(prev => ({ ...prev, email: e.target.value }))}
                        placeholder="polsek@example.com"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="polsekDescription">Deskripsi</Label>
                    <Textarea
                      id="polsekDescription"
                      value={polsekForm.description}
                      onChange={(e) => setPolsekForm(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="Deskripsi singkat tentang Polsek"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="polsekPhoto">Foto Gedung</Label>
                    <div className="flex items-center space-x-2">
                      <Input
                        id="polsekPhoto"
                        type="file"
                        accept="image/*"
                        onChange={async (e) => {
                          const file = e.target.files?.[0];
                          if (file) {
                            try {
                              toast.loading('Mengupload foto...');
                              const url = await handleFileUpload(file, 'photo');
                              setPolsekForm(prev => ({ ...prev, photo: url }));
                              toast.success('Foto berhasil diupload');
                            } catch (error) {
                              toast.error('Gagal upload foto');
                            }
                          }
                        }}
                        className="file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-sm file:bg-amber-50 file:text-amber-700 hover:file:bg-amber-100"
                      />
                      {polsekForm.photo && (
                        <div className="flex items-center space-x-2">
                          <Image className="h-4 w-4 text-green-600" alt="Photo uploaded icon" />
                          <span className="text-sm text-green-600">Foto terupload</span>
                        </div>
                      )}
                    </div>
                    {polsekForm.photo && (
                      <div className="mt-2">
                        <img 
                          src={polsekForm.photo} 
                          alt="Foto Gedung Polsek preview" 
                          className="h-16 w-auto object-contain border rounded"
                        />
                      </div>
                    )}
                  </div>

                  <div className="border-t pt-4">
                    <h3 className="font-medium mb-4">Data Kapolsek</h3>
                    <div className="grid grid-cols-3 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="kapolsekName">Nama Kapolsek</Label>
                        <Input
                          id="kapolsekName"
                          value={polsekForm.kapolsekName}
                          onChange={(e) => setPolsekForm(prev => ({ ...prev, kapolsekName: e.target.value }))}
                          placeholder="Nama lengkap"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="kapolsekNRP">NRP</Label>
                        <Input
                          id="kapolsekNRP"
                          value={polsekForm.kapolsekNRP}
                          onChange={(e) => setPolsekForm(prev => ({ ...prev, kapolsekNRP: e.target.value }))}
                          placeholder="Nomor Register Polisi"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="kapolsekPangkat">Pangkat</Label>
                        <Input
                          id="kapolsekPangkat"
                          value={polsekForm.kapolsekPangkat}
                          onChange={(e) => setPolsekForm(prev => ({ ...prev, kapolsekPangkat: e.target.value }))}
                          placeholder="Contoh: AKP"
                        />
                      </div>
                    </div>
                  </div>

                  <DialogFooter>
                    <Button type="button" variant="outline" onClick={() => setIsPolsekDialogOpen(false)}>
                      Batal
                    </Button>
                    <Button type="submit" disabled={submitting}>
                      {submitting ? 'Menyimpan...' : (editingPolsek ? 'Perbarui' : 'Simpan')}
                    </Button>
                  </DialogFooter>
                </form>
              </DialogContent>
            </Dialog>
          </div>

          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
              <p className="mt-2 text-muted-foreground">Memuat data...</p>
            </div>
          ) : polsekList.length === 0 ? (
            <Alert>
              <AlertDescription>
                Belum ada data Polsek. Klik "Tambah Polsek" untuk menambahkan data pertama.
              </AlertDescription>
            </Alert>
          ) : (
            <div className="grid gap-4">
              {polsekList.map((polsek) => (
                <Card key={polsek.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <Building2 className="h-5 w-5 text-primary" />
                        <div>
                          <CardTitle className="text-lg">{polsek.name}</CardTitle>
                          <CardDescription className="flex items-center space-x-2 mt-1">
                            <MapPin className="h-3 w-3" />
                            <span>{polsek.address}</span>
                          </CardDescription>
                          <Badge variant="secondary" className="mt-2">
                            {polsek.polres.name}
                          </Badge>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleEditPolsek(polsek)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setDeleteConfirm({ type: 'polsek', id: polsek.id, name: polsek.name })}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      {polsek.phone && (
                        <div className="flex items-center space-x-2">
                          <Phone className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm">{polsek.phone}</span>
                        </div>
                      )}
                      {polsek.email && (
                        <div className="flex items-center space-x-2">
                          <Mail className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm">{polsek.email}</span>
                        </div>
                      )}
                      {polsek.website && (
                        <div className="flex items-center space-x-2">
                          <Globe className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm">{polsek.website}</span>
                        </div>
                      )}
                      {polsek.fax && (
                        <div className="flex items-center space-x-2">
                          <span className="text-sm">Fax: {polsek.fax}</span>
                        </div>
                      )}
                    </div>

                    {polsek.description && (
                      <p className="text-sm text-muted-foreground">{polsek.description}</p>
                    )}

                    {(polsek.kapolsekName || polsek.kapolsekNRP || polsek.kapolsekPangkat) && (
                      <div className="border-t pt-4">
                        <div className="flex items-center space-x-2 mb-2">
                          <Shield className="h-4 w-4" />
                          <span className="font-medium text-sm">Kapolsek</span>
                        </div>
                        <div className="grid grid-cols-3 gap-4 text-sm">
                          {polsek.kapolsekName && (
                            <div>
                              <span className="font-medium">Nama:</span> {polsek.kapolsekName}
                            </div>
                          )}
                          {polsek.kapolsekNRP && (
                            <div>
                              <span className="font-medium">NRP:</span> {polsek.kapolsekNRP}
                            </div>
                          )}
                          {polsek.kapolsekPangkat && (
                            <div>
                              <span className="font-medium">Pangkat:</span> {polsek.kapolsekPangkat}
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={!!deleteConfirm} onOpenChange={() => setDeleteConfirm(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Konfirmasi Hapus</DialogTitle>
            <DialogDescription>
              Apakah Anda yakin ingin menghapus {deleteConfirm?.type === 'polres' ? 'Polres' : 'Polsek'} "{deleteConfirm?.name}"?
              {deleteConfirm?.type === 'polres' && ' Semua Polsek terkait juga akan dihapus.'}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteConfirm(null)}>
              Batal
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Hapus
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      </div>
    </AdminSidebar>
  );
}