"use client";

import { useState } from 'react';
import { Lock, Building2, Plus, Image as ImageIcon, MapPin } from 'lucide-react';
import dynamic from 'next/dynamic';

const LocationPicker = dynamic(() => import('./LocationPicker'), { ssr: false });

export default function AdminPage() {
 const [isAuthenticated, setIsAuthenticated] = useState(false);
 const [passwordAttempt, setPasswordAttempt] = useState('');
 
 const [title, setTitle] = useState('');
 const [propertyType, setPropertyType] = useState('Agricultural');
 const [status, setStatus] = useState('Available');
 const [price, setPrice] = useState('');
 const [area, setArea] = useState('');
 const [city, setCity] = useState('');
 const [videoUrl, setVideoUrl] = useState('');
 const [photoUrl, setPhotoUrl] = useState('');
 
 const [lat, setLat] = useState(12.9716);
 const [lng, setLng] = useState(77.5946);

 const [loading, setLoading] = useState(false);
 const [message, setMessage] = useState('');

 const handleLogin = (e: any) => {
  e.preventDefault();
  if (passwordAttempt === 'zameen123') {
   setIsAuthenticated(true);
  } else {
   alert('Incorrect Password');
  }
 };

 const handleSubmit = async (e: any) => {
  e.preventDefault();
  setLoading(true);
  
  let finalVideoUrl = videoUrl;
  if (finalVideoUrl.includes('youtube.com/watch?v=')) {
   finalVideoUrl = finalVideoUrl.replace('watch?v=', 'embed/');
   finalVideoUrl = finalVideoUrl.split('&')[0];
  } else if (finalVideoUrl.includes('youtu.be/')) {
   finalVideoUrl = finalVideoUrl.replace('youtu.be/', 'youtube.com/embed/');
   finalVideoUrl = finalVideoUrl.split('?')[0];
  }

  try {
   const res = await fetch('/api/properties', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
     title,
     propertyType,
     status,
     price: parseFloat(price),
     area: parseFloat(area),
     areaUnit: 'Acre',
     address: city,
     city,
     latitude: lat,
     longitude: lng,
     features: [],
     photos: photoUrl ? [photoUrl] : ['https://images.pexels.com/photos/30557705/pexels-photo-30557705.jpeg?auto=compress&cs=tinysrgb&w=800'],
     videos: finalVideoUrl ? [finalVideoUrl] : []
    })
   });
   
   if (res.ok) {
    setMessage('Property successfully published to Zameen Map!');
    setTitle('');
    setPrice('');
    setArea('');
    setCity('');
    setPhotoUrl('');
    setVideoUrl('');
   } else {
    setMessage('Error publishing property.');
   }
  } catch (err) {
   setMessage('Network error.');
  }
  
  setLoading(false);
 };

 if (!isAuthenticated) {
  return (
   <div className="min-h-screen bg-slate-50 flex flex-col items-center justify-center p-4">
    <form onSubmit={handleLogin} className="bg-white p-8 rounded-3xl shadow-sm border border-slate-200 max-w-sm w-full flex flex-col items-center gap-6">
     <div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center">
      <Lock className="w-8 h-8" />
     </div>
     <div className="text-center">
      <h1 className="text-2xl font-bold text-slate-900 ">Admin Access</h1>
      <p className="text-slate-500 mt-2 text-sm">Please enter the master password to manage properties.</p>
     </div>
     <input 
      type="password" 
      value={passwordAttempt}
      onChange={e => setPasswordAttempt(e.target.value)}
      className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-center tracking-widest text-lg font-bold text-slate-800 " 
      placeholder="••••••••" 
     />
     <button type="submit" className="w-full bg-slate-900 text-white font-bold h-12 rounded-xl">Unlock Portal</button>
    </form>
   </div>
  );
 }

 return (
  <div className="min-h-screen bg-slate-50 p-8">
   <div className="max-w-3xl mx-auto bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
    <div className="bg-slate-900 p-6 text-white flex items-center justify-between">
     <div>
      <h1 className="text-2xl font-bold">Zameen Admin Portal</h1>
      <p className="text-slate-400 text-sm mt-1">Upload and manage properties securely</p>
     </div>
     <Building2 className="w-8 h-8 text-emerald-400" />
    </div>
    
    <form onSubmit={handleSubmit} className="p-8 space-y-8">
     {message && (
      <div className={`p-4 rounded-xl text-sm font-semibold ${message.includes('Error') ? 'bg-red-50 text-red-700' : 'bg-emerald-50 text-emerald-700'}`}>
       {message}
      </div>
     )}
     
     <div className="space-y-6">
      <h2 className="text-lg font-bold border-b pb-2 flex items-center gap-2"><Building2 className="w-5 h-5 text-emerald-600"/> Basic Details</h2>
      <div className="grid grid-cols-2 gap-6">
       <div className="space-y-2 col-span-2">
        <label className="text-sm font-semibold text-slate-700 ">Property Title</label>
        <input required value={title} onChange={e => setTitle(e.target.value)} type="text" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. 5 Acres Premium Plot" />
       </div>
       
       <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-700 ">Type</label>
        <select value={propertyType} onChange={e => setPropertyType(e.target.value)} className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 ">
         <option>Agricultural</option>
         <option>Commercial</option>
         <option>Residential</option>
        </select>
       </div>
       
       <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-700 ">Status</label>
        <select value={status} onChange={e => setStatus(e.target.value)} className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 ">
         <option>Available</option>
         <option>Sold</option>
         <option>Reserved</option>
        </select>
       </div>
       
       <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-700 ">Price (₹)</label>
        <input required value={price} onChange={e => setPrice(e.target.value)} type="number" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. 15000000" />
       </div>
       
       <div className="space-y-2">
        <label className="text-sm font-semibold text-slate-700 ">Size (Acres)</label>
        <input required value={area} onChange={e => setArea(e.target.value)} type="number" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. 2.5" />
       </div>
      </div>
     </div>

     <div className="space-y-6">
      <h2 className="text-lg font-bold border-b pb-2 flex items-center gap-2"><MapPin className="w-5 h-5 text-emerald-600"/> Location Details</h2>
      
      <div className="space-y-2">
       <label className="text-sm font-semibold text-slate-700 ">City / Address</label>
       <input required value={city} onChange={e => setCity(e.target.value)} type="text" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. Bengaluru" />
      </div>

      <div className="space-y-2">
       <label className="text-sm font-semibold text-slate-700 ">Pin exactly on map</label>
       <LocationPicker lat={lat} lng={lng} onChange={(newLat, newLng) => { setLat(newLat); setLng(newLng); }} />
       <p className="text-xs text-slate-500 flex justify-between px-1 mt-1">
        <span>Lat: {lat.toFixed(6)}</span>
        <span>Lng: {lng.toFixed(6)}</span>
       </p>
      </div>
     </div>

     <div className="space-y-6">
      <h2 className="text-lg font-bold border-b pb-2 flex items-center gap-2"><ImageIcon className="w-5 h-5 text-emerald-600"/> Media</h2>
      
      <div className="space-y-2">
       <label className="text-sm font-semibold text-slate-700 ">Cover Photo URL</label>
       <input value={photoUrl} onChange={e => setPhotoUrl(e.target.value)} type="url" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. https://example.com/photo.jpg" />
       {photoUrl && <img src={photoUrl} alt="Preview" className="h-24 rounded-lg object-cover border border-slate-200 mt-2" />}
      </div>

      <div className="space-y-2">
       <label className="text-sm font-semibold text-slate-700 ">YouTube Video URL</label>
       <input value={videoUrl} onChange={e => setVideoUrl(e.target.value)} type="url" className="w-full border border-slate-200 rounded-xl h-12 px-4 outline-none focus:border-emerald-500 text-slate-800 " placeholder="e.g. https://youtube.com/watch?v=..." />
      </div>
     </div>
     
     <button disabled={loading} type="submit" className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold h-14 rounded-xl flex items-center justify-center gap-2 transition-colors disabled:opacity-50 text-lg shadow-lg">
      {loading ? 'Publishing...' : <><Plus className="w-6 h-6" /> Publish to Live Map</>}
     </button>
    </form>
   </div>
  </div>
 );
}
