"use client";

import React, { useState } from "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, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ASSET_TYPES, MARKETS } from "@/lib/utils";
import { Loader2, Save, Check, Bell, Mail, Phone } from "lucide-react";
import { useToast } from "@/components/ui/toast";

function ToggleSwitch({ enabled, onChange, label, description }: { enabled: boolean; onChange: (v: boolean) => void; label: string; description: string }) {
  return (
    <div className="flex items-center justify-between p-3 rounded-lg hover:bg-navy-25 transition-colors">
      <div>
        <p className="text-sm font-medium text-navy-800">{label}</p>
        <p className="text-xs text-navy-500">{description}</p>
      </div>
      <button
        type="button"
        onClick={() => onChange(!enabled)}
        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${enabled ? "bg-gold-500" : "bg-navy-200"}`}
      >
        <span className={`inline-block h-4 w-4 rounded-full bg-white shadow-sm transform transition-transform ${enabled ? "translate-x-6" : "translate-x-1"}`} />
      </button>
    </div>
  );
}

export default function PreferencesPage() {
  const { addToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [saved, setSaved] = useState(false);
  const [selectedAssetTypes, setSelectedAssetTypes] = useState<string[]>([
    "Multifamily",
    "Hospitality",
  ]);
  const [selectedLocations, setSelectedLocations] = useState<string[]>([
    "Miami, FL",
    "Tampa, FL",
  ]);
  const [notifications, setNotifications] = useState({
    emailDeals: true,
    smsDeals: false,
    emailDigest: true,
    marketUpdates: false,
  });
  const [formData, setFormData] = useState({
    price_min: "15000000",
    price_max: "100000000",
    cap_rate_min: "4.0",
    cap_rate_max: "6.0",
    preferences: "1031 exchange buyer, luxury properties, waterfront",
  });

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    setSaved(false);
  };

  const toggleAssetType = (type: string) => {
    setSelectedAssetTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
    setSaved(false);
  };

  const toggleLocation = (loc: string) => {
    setSelectedLocations((prev) =>
      prev.includes(loc) ? prev.filter((l) => l !== loc) : [...prev, loc]
    );
    setSaved(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setLoading(false);
    setSaved(true);
    addToast({
      type: "success",
      title: "Preferences Saved!",
      description: "Your acquisition criteria have been updated. You'll receive better-matched deals.",
      duration: 4000,
    });
  };

  return (
    <div className="max-w-2xl mx-auto space-y-5 sm:space-y-6 animate-page-in">
      <div>
        <h1 className="text-xl sm:text-2xl font-bold text-navy-900">Acquisition Preferences</h1>
        <p className="text-sm text-navy-500 mt-1">
          Update your criteria to receive better-matched deal opportunities.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <Card className="hover-lift">
          <CardHeader>
            <CardTitle className="text-lg">Target Asset Types</CardTitle>
            <CardDescription>Select all property types you&apos;re interested in</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {ASSET_TYPES.map((type) => (
                <button
                  key={type}
                  type="button"
                  onClick={() => toggleAssetType(type)}
                  className={`text-sm px-4 py-2.5 rounded-lg border transition-all min-h-[44px] active:scale-[0.96] ${
                    selectedAssetTypes.includes(type)
                      ? "bg-navy-800 text-white border-navy-800 shadow-sm"
                      : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"
                  }`}
                >
                  {type}
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="hover-lift">
          <CardHeader>
            <CardTitle className="text-lg">Target Locations</CardTitle>
            <CardDescription>Where are you looking to acquire?</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2 max-h-48 overflow-y-auto">
              {MARKETS.map((loc) => (
                <button
                  key={loc}
                  type="button"
                  onClick={() => toggleLocation(loc)}
                  className={`text-sm px-4 py-2.5 rounded-lg border transition-all min-h-[44px] active:scale-[0.96] ${
                    selectedLocations.includes(loc)
                      ? "bg-navy-800 text-white border-navy-800 shadow-sm"
                      : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"
                  }`}
                >
                  {loc}
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="hover-lift">
          <CardHeader>
            <CardTitle className="text-lg">Price & Cap Rate Range</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="price_min" className="text-xs text-navy-500 font-light">Min Price ($)</Label>
                <Input
                  id="price_min"
                  type="number"
                  value={formData.price_min}
                  onChange={(e) => handleChange("price_min", e.target.value)}
                  className="mt-1.5"
                />
              </div>
              <div>
                <Label htmlFor="price_max" className="text-xs text-navy-500 font-light">Max Price ($)</Label>
                <Input
                  id="price_max"
                  type="number"
                  value={formData.price_max}
                  onChange={(e) => handleChange("price_max", e.target.value)}
                  className="mt-1.5"
                />
              </div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="cap_min" className="text-xs text-navy-500 font-light">Min Cap Rate (%)</Label>
                <Input
                  id="cap_min"
                  type="number"
                  step="0.1"
                  value={formData.cap_rate_min}
                  onChange={(e) => handleChange("cap_rate_min", e.target.value)}
                  className="mt-1.5"
                />
              </div>
              <div>
                <Label htmlFor="cap_max" className="text-xs text-navy-500 font-light">Max Cap Rate (%)</Label>
                <Input
                  id="cap_max"
                  type="number"
                  step="0.1"
                  value={formData.cap_rate_max}
                  onChange={(e) => handleChange("cap_rate_max", e.target.value)}
                  className="mt-1.5"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="hover-lift">
          <CardHeader>
            <CardTitle className="text-lg">Additional Preferences</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="relative">
              <Textarea
                placeholder="Value-add opportunities, 1031 exchange requirements, specific tenant types..."
                value={formData.preferences}
                onChange={(e) => handleChange("preferences", e.target.value)}
                rows={4}
                maxLength={500}
              />
              <span className="absolute bottom-2 right-3 text-xs text-navy-400">
                {formData.preferences.length}/500
              </span>
            </div>
          </CardContent>
        </Card>

        {/* Notification Preferences */}
        <Card className="hover-lift">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <Bell className="h-5 w-5 text-navy-500" />
              Notification Preferences
            </CardTitle>
            <CardDescription>Choose how you want to receive deal alerts</CardDescription>
          </CardHeader>
          <CardContent className="space-y-1">
            <ToggleSwitch
              enabled={notifications.emailDeals}
              onChange={(v) => { setNotifications((p) => ({ ...p, emailDeals: v })); setSaved(false); }}
              label="Email — New Deals"
              description="Get notified via email when new matching deals are available"
            />
            <ToggleSwitch
              enabled={notifications.smsDeals}
              onChange={(v) => { setNotifications((p) => ({ ...p, smsDeals: v })); setSaved(false); }}
              label="SMS — New Deals"
              description="Receive SMS alerts for high-priority matching deals"
            />
            <ToggleSwitch
              enabled={notifications.emailDigest}
              onChange={(v) => { setNotifications((p) => ({ ...p, emailDigest: v })); setSaved(false); }}
              label="Weekly Digest"
              description="Receive a weekly summary of new deals and market activity"
            />
            <ToggleSwitch
              enabled={notifications.marketUpdates}
              onChange={(v) => { setNotifications((p) => ({ ...p, marketUpdates: v })); setSaved(false); }}
              label="Market Updates"
              description="Get insights on market trends in your target locations"
            />
          </CardContent>
        </Card>

        <Button type="submit" variant="gold" className="w-full active:scale-[0.98] transition-transform" size="lg" disabled={loading}>
          {loading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Saving...
            </>
          ) : saved ? (
            <>
              <Check className="mr-2 h-4 w-4" />
              Preferences Saved
            </>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Save Preferences
            </>
          )}
        </Button>
      </form>
    </div>
  );
}
