import { createMemo, createSignal, For, Show } from "solid-js";
import { Building2, Globe, Plus, Search, Trash2 } from "lucide-solid";

import Modal from "~/components/modal";
import { useApp } from "~/lib/app-context";
import {
  apiListCompanies,
  apiCreateCompany,
  apiUpdateCompany,
  apiDeleteCompany
} from "~/lib/api-crm";
import type { Company } from "~/lib/types-crm";

const industryOptions = [
  "Technology",
  "Healthcare",
  "Finance",
  "Education",
  "Retail",
  "Manufacturing",
  "Consulting",
  "Media",
  "Other"
];

const sizeOptions = ["1-10", "11-50", "51-200", "201-500", "501-1000", "1000+"];

export default function CompaniesRoute() {
  const app = useApp();
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const [companies, setCompanies] = createSignal<Company[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [search, setSearch] = createSignal("");
  const [showAdd, setShowAdd] = createSignal(false);
  const [selectedId, setSelectedId] = createSignal<string | null>(null);

  // Form state
  const [name, setName] = createSignal("");
  const [domain, setDomain] = createSignal("");
  const [website, setWebsite] = createSignal("");
  const [industry, setIndustry] = createSignal("");
  const [size, setSize] = createSignal("");
  const [notes, setNotes] = createSignal("");

  const loadCompanies = async () => {
    setLoading(true);
    try {
      const list = await apiListCompanies(workspaceSlug());
      setCompanies(list);
    } catch (e) {
      console.error("Failed to load companies", e);
    }
    setLoading(false);
  };

  if (companies().length === 0) {
    loadCompanies();
  }

  const filteredCompanies = createMemo(() => {
    const q = search().toLowerCase();
    if (!q) return companies();
    return companies().filter(c =>
      c.name.toLowerCase().includes(q) ||
      c.domain.toLowerCase().includes(q) ||
      c.industry.toLowerCase().includes(q)
    );
  });

  const resetForm = () => {
    setName("");
    setDomain("");
    setWebsite("");
    setIndustry("");
    setSize("");
    setNotes("");
  };

  const handleAdd = async () => {
    if (!name().trim()) return;

    const company = await apiCreateCompany({
      workspaceSlug: workspaceSlug(),
      name: name(),
      domain: domain(),
      website: website(),
      industry: industry(),
      size: size(),
      notes: notes()
    });

    setCompanies([...companies(), company]);
    setShowAdd(false);
    resetForm();
  };

  const handleUpdate = async () => {
    const id = selectedId();
    if (!id) return;

    const updated = await apiUpdateCompany(id, {
      name: name(),
      domain: domain(),
      website: website(),
      industry: industry(),
      size: size(),
      notes: notes()
    });

    setCompanies(companies().map(c => c.id === id ? updated : c));
    setSelectedId(null);
    resetForm();
  };

  const handleDelete = async (id: string) => {
    await apiDeleteCompany(id);
    setCompanies(companies().filter(c => c.id !== id));
    if (selectedId() === id) setSelectedId(null);
  };

  const openEdit = (company: Company) => {
    setSelectedId(company.id);
    setName(company.name);
    setDomain(company.domain);
    setWebsite(company.website);
    setIndustry(company.industry);
    setSize(company.size);
    setNotes(company.notes);
  };

  return (
    <div class="flex h-full gap-6">
      {/* Main list */}
      <div class="flex-1 flex flex-col">
        <div class="flex items-center justify-between mb-4">
          <h1 class="text-2xl font-semibold">Companies</h1>
          <button
            onClick={() => { resetForm(); setShowAdd(true); }}
            class="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
          >
            <Plus class="w-4 h-4" />
            Add Company
          </button>
        </div>

        {/* Search */}
        <div class="relative mb-4">
          <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--text-muted)]" />
          <input
            type="text"
            placeholder="Search companies..."
            value={search()}
            onInput={e => setSearch(e.currentTarget.value)}
            class="w-full pl-9 pr-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
          />
        </div>

        {/* Company list */}
        <Show when={!loading()} fallback={<div class="text-[var(--text-muted)]">Loading...</div>}>
          <div class="flex-1 overflow-auto space-y-2">
            <Show when={filteredCompanies().length === 0}>
              <div class="text-center py-12 text-[var(--text-muted)]">
                No companies yet. Add your first company to get started.
              </div>
            </Show>
            <For each={filteredCompanies()}>
              {company => (
                <div
                  class="flex items-center gap-4 p-4 rounded-lg border border-[var(--border)] bg-[var(--surface)] hover:border-[var(--accent)] cursor-pointer transition-colors"
                  onClick={() => openEdit(company)}
                >
                  <div class="w-10 h-10 rounded-lg bg-[var(--secondary)] flex items-center justify-center text-white">
                    <Building2 class="w-5 h-5" />
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="font-medium truncate">{company.name}</div>
                    <div class="text-sm text-[var(--text-muted)] truncate">
                      {company.industry && <span>{company.industry}</span>}
                      {company.industry && company.size && <span> • </span>}
                      {company.size && <span>{company.size} employees</span>}
                    </div>
                  </div>
                  {company.website && (
                    <a
                      href={company.website}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={e => e.stopPropagation()}
                      class="text-[var(--text-muted)] hover:text-[var(--accent)]"
                    >
                      <Globe class="w-4 h-4" />
                    </a>
                  )}
                </div>
              )}
            </For>
          </div>
        </Show>
      </div>

      {/* Add Modal */}
      <Modal open={showAdd()} onClose={() => setShowAdd(false)} title="Add Company">
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Name *</label>
            <input
              type="text"
              value={name()}
              onInput={e => setName(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              placeholder="Company name"
            />
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Domain</label>
              <input
                type="text"
                value={domain()}
                onInput={e => setDomain(e.currentTarget.value)}
                class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                placeholder="example.com"
              />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Website</label>
              <input
                type="url"
                value={website()}
                onInput={e => setWebsite(e.currentTarget.value)}
                class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                placeholder="https://example.com"
              />
            </div>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Industry</label>
              <select
                value={industry()}
                onChange={e => setIndustry(e.currentTarget.value)}
                class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              >
                <option value="">Select industry</option>
                <For each={industryOptions}>
                  {opt => <option value={opt}>{opt}</option>}
                </For>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Company Size</label>
              <select
                value={size()}
                onChange={e => setSize(e.currentTarget.value)}
                class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              >
                <option value="">Select size</option>
                <For each={sizeOptions}>
                  {opt => <option value={opt}>{opt}</option>}
                </For>
              </select>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Notes</label>
            <textarea
              value={notes()}
              onInput={e => setNotes(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] min-h-[80px]"
            />
          </div>
          <div class="flex justify-end gap-2 pt-2">
            <button
              onClick={() => setShowAdd(false)}
              class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)]"
            >
              Cancel
            </button>
            <button
              onClick={handleAdd}
              class="px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
            >
              Add Company
            </button>
          </div>
        </div>
      </Modal>

      {/* Edit Modal */}
      <Modal open={selectedId() !== null} onClose={() => { setSelectedId(null); resetForm(); }} title="Edit Company">
        <Show when={companies().find(c => c.id === selectedId())}>
          {company => (
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium mb-1">Name *</label>
                <input
                  type="text"
                  value={name()}
                  onInput={e => setName(e.currentTarget.value)}
                  class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                />
              </div>
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-1">Domain</label>
                  <input
                    type="text"
                    value={domain()}
                    onInput={e => setDomain(e.currentTarget.value)}
                    class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-1">Website</label>
                  <input
                    type="url"
                    value={website()}
                    onInput={e => setWebsite(e.currentTarget.value)}
                    class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                  />
                </div>
              </div>
              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-1">Industry</label>
                  <select
                    value={industry()}
                    onChange={e => setIndustry(e.currentTarget.value)}
                    class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                  >
                    <option value="">Select industry</option>
                    <For each={industryOptions}>
                      {opt => <option value={opt}>{opt}</option>}
                    </For>
                  </select>
                </div>
                <div>
                  <label class="block text-sm font-medium mb-1">Company Size</label>
                  <select
                    value={size()}
                    onChange={e => setSize(e.currentTarget.value)}
                    class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
                  >
                    <option value="">Select size</option>
                    <For each={sizeOptions}>
                      {opt => <option value={opt}>{opt}</option>}
                    </For>
                  </select>
                </div>
              </div>
              <div>
                <label class="block text-sm font-medium mb-1">Notes</label>
                <textarea
                  value={notes()}
                  onInput={e => setNotes(e.currentTarget.value)}
                  class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] min-h-[80px]"
                />
              </div>
              <div class="flex justify-between pt-2">
                <button
                  onClick={() => handleDelete(company.id)}
                  class="px-4 py-2 rounded-lg text-red-500 hover:bg-red-50 dark:hover:bg-red-950"
                >
                  Delete
                </button>
                <div class="flex gap-2">
                  <button
                    onClick={() => { setSelectedId(null); resetForm(); }}
                    class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)]"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleUpdate}
                    class="px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
                  >
                    Save
                  </button>
                </div>
              </div>
            </div>
          )}
        </Show>
      </Modal>
    </div>
  );
}